loops - python two dictionaries into one? mixed up keys and values -


i've got 2 dictionaries, d1, , d2 each entry (a, b) in d1, if not key of d2 add (a,b) new dictionary each entry (a, b) in d2, if not key of d1 (i.e., not in d1) add (a,b) new dictionary example if d1 {2:3, 8:19, 6:4, 5:12} , d2 {2:5, 4:3, 3:9}, new dictionary should {8:19, 6:4, 5:12, 4:3, 3:9}. here's code far.

d3 = {} in d1.items():     if i[1] not  in d2.keys():         d3[i[0]] = d2[i[1]] 

if you're on python 2.7, can take key views of each dict, symmetric difference, , pick value each key dict had key:

result = {key: d1[key] if key in d1 else d2[key]           key in d1.viewkeys() ^ d2.viewkeys()} 

in python 3.x, it's pretty same, except viewkeys keys:

result = {key: d1[key] if key in d1 else d2[key]           key in d1.keys() ^ d2.keys()} 

before 2.7, there no dict views or dict comprehensions, can use sets , dict constructor generator expression:

result = dict((key, d1[key] if key in d1 else d2[key])               key in set(d1).symmetric_difference(d2)) 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -