Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add two python dictionaries such that the not equal thinks become zero?

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}
like image 498
user2392755 Avatar asked Dec 08 '25 10:12

user2392755


2 Answers

>>> 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}
like image 140
John La Rooy Avatar answered Dec 10 '25 01:12

John La Rooy


>>> 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}
like image 22
Ashwini Chaudhary Avatar answered Dec 09 '25 23:12

Ashwini Chaudhary