a =[{
"id":"1",
"Name":'BK',
"Age":'56'
},
{
"id":"1",
"Sex":'Male'
},
{
"id":"2",
"Name":"AK",
"Age":"32"
}]
I have a list of dictionary with a person information split in multiple dictionary as above for ex above id 1’s information is contained in first 2 dictionary , how can i get an output of below
{1: {'Name':'BK','Age':'56','Sex':'Male'}, 2: { 'Name': 'AK','Age':'32'}}
>Solution :
You can use some built in functions. groupby to group the dictionaries by id, then a defaultdict to collect the results.
from itertools import groupby
from collections import defaultdict
a =[{ "id":"1", "Name":'BK', "Age":'56' }, { "id":"1", "Sex":'Male' }, { "id":"2", "Name":"AK", "Age":"32" }]
results = defaultdict(dict)
key = lambda d: d['id']
for group_id, grouped in groupby(sorted(a, key=key), key=key):
for d in grouped:
d.pop('id')
results[group_id].update(**d)
This gives you:
>>> results
defaultdict(<type 'dict'>, {'1': {'Age': '56', 'Name': 'BK', 'Sex': 'Male'}, '2': {'Age': '32', 'Name': 'AK'}})
The defaultdict type behaves like a normal dict, except that when you reference an unknown value, a default value is returned. This means that as the dicts in a are iterated over, the values (except for id) are updated onto either an existing dict, or an automatic newly created one.
How does collections.defaultdict work?