This might be a possible duplicate. I have 2 dictionaries in this format:
dict1={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12'}
dict2={'id1':'n/a', 'id2':'12', 'key21':'value21', 'key22':'value22'}
Notice that the only common key
between the 2 dictionaries is id2
. So I want my final dict to be something like this:
dict3={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12', 'key21':'value21', 'key22':'value22'}
Also, notice that on the 2nd
dictionary. id1 is missing
, but on the final output, dict3
is using the value from dict1
because from id2
we know it's the same dictionary.
And finally, if dict2 has no matching keys with dict1, like this:
dict1={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12'}
dict2={'id1':'n/a', 'id2':'somevalue', 'key21':'value21', 'key22':'value22'}
Can then dict3 be dict2 with the dict1 keys but the values set to 'n/a'
?? Like this:
dict3={'id1':'n/a', 'id2':'somevalue', 'key21':'value21', 'key22':'value22', 'id2':'n/a', 'key11':'n/a', 'key12':'n/a'}
I'm traversing 2 lists of dictionaries to do this. So my code so far is this:
for d1 in dlist1:
for d2 in dlist2:
if d1['id1']==d2['id1']:
if d1['id2'] == 'n/a':
d1['id2'] = d2['id2']
d1['key21'] = d2['key21']
# adding the new key-value pairs to dictionary 1, one-by-one and so on ...
In short, I'm either adding new fields to one of the nodes in dlist1
or adding an entirely new node to dlist1
.
My question is: Is there a quicker pythonic way to do this? Because my implementation is giving me KeyError's