I need a little bit of help here. I am a new python coder. I need a lot of help. So, I want to add the different variables in two dictionaries. An example is:
x = {'a':1, 'b':2}
y = {'b':1, 'c':2}
I want to replace these values such that it looks like:
x = {'a':1, 'b':2, 'c':0}
y = {'a':0, 'b':1, 'c':2}
>>> x = {'a':1, 'b':2}
>>> y = {'b':1, 'c':2}
>>> for k in y:
... x.setdefault(k, 0)
...
0
2
>>> for k in x:
... y.setdefault(k, 0)
...
0
2
1
>>> x
{'a': 1, 'c': 0, 'b': 2}
>>> y
{'a': 0, 'c': 2, 'b': 1}
>>> x = {'a':1, 'b':2}
>>> y = {'b':1, 'c':2}
>>> keys = x.viewkeys() | y.viewkeys() #returns union of keys in x and y
>>> x = {k : x.get(k,0) for k in keys}
>>> y = {k : y.get(k,0) for k in keys}
>>> x
{'a': 1, 'c': 0, 'b': 2}
>>> y
{'a': 0, 'c': 2, 'b': 1}
change the dict in-place:
>>> x = {'a':1, 'b':2}
>>> y = {'b':1, 'c':2}
>>> diff_x = y.viewkeys() - x.viewkeys()
>>> diff_y = x.viewkeys() - y.viewkeys()
#if you're using a mutable object as value instead of 0,
#then you've to use a dict comprehension instead of dict.fromkeys.
>>> x.update(dict.fromkeys(diff_x,0))
>>> y.update(dict.fromkeys(diff_y,0))
>>> x
{'a': 1, 'c': 0, 'b': 2}
>>> y
{'a': 0, 'c': 2, 'b': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With