Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List of Dictionary – How to combine a list of dictionary Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading