Looping and splitting Object

Question:

how to loop on object and split it by ":" into separate one

{
 labs:  [1,2,":",3,4],
 level: [1,2,":",3,4]
}

Expected Output:

{
 labs:  [1,2],
 level: [1,2]
}

{
 labs:   [3,4],
 level : [3,4]
}
Asked By: Mohamed

||

Answers:

You can use itertools.groupby from the standard library to group the numbers that are not ":". With that you can use zip to pair off the groups.

from itertools import groupby

d = {
 "labs":  [1,2,":",3,4],
 "level": [10,20,":",30,40]
}

groups = [[(k, list(g)) for b, g in groupby(v, key=lambda n:n != ':') if b] 
          for k, v in d.items()
         ]

list(map(dict, zip(*groups)))
# [
#     {'labs': [1, 2], 'level': [10, 20]}, 
#     {'labs': [3, 4], 'level': [30, 40]}
# ]

This should work with arbitrary data. For example with input like:

d = {
 "labs":  [1,2,":",3,4,":", 5, 6],
 "level": [10,20,":",30,40,":",50, 60],
 "others":[-1,-2,":",-3,-4,":",-5,-6]
}

You will get:

[{'labs': [1, 2], 'level': [10, 20], 'others': [-1, -2]},
 {'labs': [3, 4], 'level': [30, 40], 'others': [-3, -4]},
 {'labs': [5, 6], 'level': [50, 60], 'others': [-5, -6]}
]

But it does expect the lists to be the same length because the way zip() works. If that’s not a good assumption you will need to decide what to do with uneven lists. In that case itertools.zip_longest() will probably be helpful.

Answered By: Mark

Use javaScript to resolve this problem, maybe the code is not the best

const obj = {
    labs:  [1,2,":",3,4,":",5,6],
    level: [1,2,":",3,4,":",7,8],
    others: [1,2,":",3,4,":",9,10]
}

const format = (obj = {}, result = []) => {
    const keys = Object.keys(obj);
    for ( key of keys) {
        const itemValues = obj[key].toString().split(':');
        let tempRes = {}
        itemValues.map((itemValue, index) => {
            Object.assign(tempRes, {
                [`${keys[index]}`]: itemValue.replace(/^(,)+|(,)+$/g, '').split(',').map(Number)// you can format value here 
            })
        })
        result.push(tempRes);
    }
    return result;
}

console.log(format(obj))

You will get

[
  { labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 5, 6 ] },
  { labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 7, 8 ] },
  { labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 9, 10 ] }
]
Answered By: lwz
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.