[英]How to change keys of ordered dict to that of keys from other ordered dict in Python?
I have two ordered dicts D1
and D2
. 我有两个命令字典
D1
和D2
。 I want to assign key names of D2
to D1
(overwrite existing key names of D1
). 我想的键名分配
D2
到D1
(覆盖现有的键名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 现在我想将
D2
键名分配给D1
以便D1
成为
{'first_new_key': 10, 'second_new_key': 20}
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?): 如果您喜欢1-liners(这就是为什么我们有python,对吗?):
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
. 我发现您想覆盖
D1
。 In that case you can simply do: 在这种情况下,您可以简单地执行以下操作:
D1 = dict(zip(D2.keys(), D1.values()))
EDIT 2 编辑2
As Barmar mentioned in another answer, in order to have ordered dictionaries, one must use collections.OrderedDict()
. 正如Barmar在另一个答案中提到的那样,为了拥有有序字典,必须使用
collections.OrderedDict()
。
noamgot's answer will work if it's OK to create a new dictionary. 如果可以创建新词典,则noamgot的答案将起作用。 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. Python 3中需要
list()
包装器,因为items()
是生成器,并且您无法修改要迭代的字典。
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.