Home > Mobile >  Segregate a list of dictionary into multiple lists
Segregate a list of dictionary into multiple lists

Time:12-29

I have a list of dictionaries which contains below data

[{
  "col1":"1",
  "col2":"a"
},{
  "col1":"2",
  "col2":"b"
},{
  "col1":"3",
  "col2":"c"
}]

Here my dictionary key fields are dynamic ( e.g. col1, col2).

I want to segregate this dictionary data into multiple list based on key field grouping. Result which i'm trying to achieve should look like this

{
  "col1":["1","2","3"],
  "col2":["a","b","c"]
}

Could anyone tell me how to do it in few lines rather then writing multiple for loops?

CodePudding user response:

What about this solution? You could try this collections.defaultdict() to group all items with the same key: To make it readable it's perfect fine to use loops.

from collections import defaultdict

dd = defaultdict(list)

lst = [{
  "col1":"1", "col2":"a"
},{
  "col1":"2", "col2":"b"
},{
  "col1":"3", "col2":"c"
}]

for d in lst:
    #print(d)  # d is a dict
    for k, v in d.items():
        dd[k].append(v)
        
print(dd)

Results:

defaultdict(<class 'list'>, {'col1': ['1', '2', '3'], 'col2': ['a', 'b', 'c']})
  • Related