Reputation: 51
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}
The order of variables has to be same. Please help me.
Upvotes: 0
Views: 103
Reputation: 3817
The first thing is, that Python dicts are unordered, but if you need ordering you can use collections.OrderedDict.
But for normal dicts you can add more entries in this way:
x = {'a':1, 'b':2}
y = {'b':1, 'c':2}
x.update({'c':0})
y.update({'b':1})
Or this way:
x.update(c=0)
y.update(b=1)
Or (comment by iamthepiguy) in this way:
x['c'] = 0
y['b'] = 1
If you want to update/add many entries at the same time you could use this:
x.update({'c':0,'d':5,'x':4}
# or the same in the other way
x.update(c=0,d=5,x=4)
You can also change entries with the methods showed above. Simply use a key that is already in the dict and a new value eg. x['a']=7
.
For more informations about dict.update look here
Upvotes: 5
Reputation: 373
For an OrderedDict example:
import collections
dx = {'a':1, 'b':2}
dy = {'b':1, 'c':2}
dx['c'] = 0
dy['a'] = 0
x = collections.OrderedDict(sorted(dx.items(), key=lambda t: t[0])) # lambda sorts dictionary items by key, and puts in ordered dictionary
y = collections.OrderedDict(sorted(dy.items(), key=lambda t: t[0]))
The result of this is:
>>> x
OrderedDict([('a', 1), ('b', 2), ('c', 0)])
>>> y
OrderedDict([('a', 0), ('b', 1), ('c', 2)])
Hope that answers your question.
Upvotes: 3