Reputation: 4926
I have two ordered dicts D1
and D2
. I want to assign key names of D2
to D1
(overwrite existing key names of D1
). How to do that?
Example:
D1 = {'first_key': 10, 'second_key': 20}
D2 = {'first_new_key': 123, 'second_new_key': 456}
Now I want to assign key names of D2
to D1
so that D1
becomes
{'first_new_key': 10, 'second_new_key': 20}
Upvotes: 2
Views: 2638
Reputation: 4091
here's a solution:
keys = D2.keys()
values = D1.values()
new_dict = dict(zip(keys, values))
If your'e into 1-liners (that's why we have python, right?):
new_dict = dict(zip(D2.keys(), D1.values()))
As mentioned in the comments, the insertion order between the 2 dictionaries must match.
EDIT
I figured out that you want to overwrite D1
. In that case you can simply do:
D1 = dict(zip(D2.keys(), D1.values()))
EDIT 2
As Barmar mentioned in another answer, in order to have ordered dictionaries, one must use collections.OrderedDict()
.
Upvotes: 5
Reputation: 780899
noamgot's answer will work if it's OK to create a new dictionary. If you need to modify the existing dictionary in place:
for (old_key, old_val), new_key in zip(list(D1.items()), D2.keys()):
del D1[old_key]
D1[new_key] = old_val
The list()
wrapper are needed in Python 3 because items()
is a generator, and you can't modify the dict being iterated over.
Upvotes: 2
Reputation: 71451
The simplest way is mere dictionary assignment:
D1 = {'first_key': 10, 'second_key': 20}
D2 = {'first_new_key': 123, 'second_new_key': 456}
D2['first_new_key'] = D1['first_key']
D2['second_new_key'] = D1['second_key']
However, for larger dictionaries, it may be better to use dictionary comprehension:
D1 = {a:D1[a.split('_')[0]+"_key"] for a, _ in D2.items()}
Output:
{'second_new_key': 20, 'first_new_key': 10}
Upvotes: 0