EDIT: Based on the exact output you need, try this -
- You can use collections.defaultdict for this purpose.
- You have to explicitly mentioned which keys you what to aggregate as a list. That is what the
listKeys
variable is for below.
- This iterates over the list of dicts and then the dict items itself, and if the key is in
listkeys
it appends it as a list, otherwise it simply updates with the latest value.
l = [{'Email Address': 'abc@xyz.com', 'Email Address Type (Primary/Alternate)': 'Primary Email'}, {'Email Address': 'abc@xyz.com', 'Email Address Type (Primary/Alternate)': 'Primary Email'}, {'Email Address': 'abc@xyz.com', 'Email Address Type (Primary/Alternate)': 'Primary Email'}]
listKeys = ['Email Address'] #keys where you want output to be a list
d = defaultdict(list)
for i in l:
for k,v in i.items():
if k in listKeys:
d[k].append(v)
else:
d[k]=v
output = dict(d)
output
{'Email Address': ['abc@xyz.com', 'abc@xyz.com', 'abc@xyz.com'],
'Email Address Type (Primary/Alternate)': 'Primary Email'}
1. Repeated items in list
You can use collections.defaultdict
for this purpose
from collections import defaultdict
d = defaultdict(list)
for i in l:
for k,v in i.items():
d[k].append(v)
output = dict(d)
{'Email Address': ['abc@xyz.com', 'abc@xyz.com', 'abc@xyz.com'],
'Email Address Type (Primary/Alternate)': ['Primary Email',
'Primary Email',
'Primary Email']}
2. Unique items in list
If you only want unique items -
d = defaultdict(list)
for i in l:
for k,v in i.items():
if v not in d[k]:
d[k].append(v)
output = dict(d)
output
{'Email Address': ['abc@xyz.com'],
'Email Address Type (Primary/Alternate)': ['Primary Email']}