merge the list of dictionaries into one dict closed

Create a dictionary of lists first then append the values from the original data.

It seems odd that you want a list of dictionaries instead of a single dictionary, so I provided both.

Try this code:

my_list = [{'qwerty': 'hello'},
           {'asdfg': 'watermelon'},
           {'asdfg': 'banana'}]

keys = set([list(i.keys())[0] for i in my_list])

dd = {k:[] for k in keys}

for d in my_list:
  dd[list(d.keys())[0]].append(list(d.values())[0])

print(dd)  # single dictionary

dd2 = [{x:dd[x]} for x in dd]

print(dd2)  # list of dictionaries

Output

{'qwerty': ['hello'], 'asdfg': ['watermelon', 'banana']}

[{'qwerty': ['hello']}, {'asdfg': ['watermelon', 'banana']}]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top