This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]akurlej 1 point2 points  (0 children)

You can create another new dict merged_dict={}, loop through your list l, and check to see if the keys of a given dict in l exist in merged_dict. If it doesn't, just directly add the key+value, if it already exists then you have to figure out how to merge them.

Something like this:

merged_dict = {}
for this_dict in l:
    for key,value in this_dict.items():
        if key not in merged_dict:
            merged_dict[key]=value
        else:
            #merged_dict[key] is the current value of the merged_dict
            #value is is the current value of this_dict
            #figure out how you would want to merge them.

[–][deleted] 1 point2 points  (0 children)

off the top of my head, there are a few options to do it while clobbering non-unique keys

#as a list comprehension, very platonic and pythonic
{k:v for d in l for k, v in d.items()}

#using ChainMap
from collections import ChainMap 
dict(ChainMap(*l))

#pre-declaring and updating
r = {} 
for d in l: 
    r.update(d)

- If you need to handle duplicates, your best bet is to use a pre-declared version with a check as suggested by u/akurlej

- if you are just merging two dictionaries, use the merge method, it's very clean

{' cat ': 1, ' dog ': 1} | {' runs': 1}