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:
{'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': []}