2

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

Mixalis
  • 532
  • 5
  • 17
  • What you mean by *if dict2 has no matching keys with dict1*? both dictionaries have multiple common keys in your second example ? – Mazdak Aug 18 '16 at 10:25
  • @kasramvd they have common keys, but the values of those keys are different. So that means `dict2 doesn't match dict1`. In order for the 2 dicts to match, and merge them, it has to be that either `id1 or id2 or both` key-value pairs are the same on both dictionaries – Mixalis Aug 18 '16 at 10:30
  • Possible duplicate of [how-can-i-merge-two-python-dictionaries-in-a-single-expression](http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression) – BPL Aug 18 '16 at 10:35
  • @BPL it's not entirely a duplicate because it doesnt handle the fields that will be left blank. – Mixalis Aug 18 '16 at 10:43

0 Answers0