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 dictionaries into one dictionary with condition

I have a list of dictionaries:

foo = [{'name':'John Doe', 'customer':'a'},
       {'name':'John Doe', 'customer':'b'},
       {'name':'Jenny Wang', 'customer':'c'}, 
       {'name':'Mary Rich', 'customer': None}
      ] 

Is there a way to get the value of the first key and set it as the new key and the value of the new dict is the value of the 2nd key.

Expected result:

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

{'John Doe':['a', 'b'], 'Jenny Wang':['c'], 'Mary Rich':[]}

>Solution :

You could use dict.setdefault. The idea is initialize an empty list as a value for each key. Then check if a name already exists as a key and append non-None values to it (is not None check is necessary because if it’s left out, other not-truthy values (such as False) may get left out; thanks @Grismar)

out = {}
for d in foo:
    out.setdefault(d['name'], [])
    if d['customer'] is not None:
        out[d['name']].append(d['customer'])

Output:

{'John Doe': ['a', 'b'], 'Jenny Wang': ['c'], 'Mary Rich': []}
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