Home > other >  List of dictionaries into one dictionary with condition
List of dictionaries into one dictionary with condition

Time:02-21

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

CodePudding user response:

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

CodePudding user response:

There is a function in itertools called groupby. It splits your input list on a criteria you provide. It can then look like that.

from itertools import groupby

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

def func_group(item):
    return item['name']

def main():
    for key, value in groupby(foo, func_group):
        print(key)
        print(list(value))

That leads not completely to your expected output but comes close:

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