[英]Return values from one dictionary by comparing keys from another dictionary
I have two dictionaries and I want to get the values of the first dictionary for the keys of the second.我有两个字典,我想获取第二个字典的第一个字典的值。 Both the dictionaries have the same keys but in different order.
两个字典具有相同的键,但顺序不同。 For example:
例如:
dict1={'a':1,'b':1,'c':0,'d':0,'e':1,'f':0,'g':1}
This is the first dictionary.这是第一本词典。 And the second dictionary is:
第二本字典是:
dict2={'c':3,'b':2,'a':1,'d':1,'e':0,'g':0,'f':0}
I want to get the values corresponding to the first dictionary but in the order of keys of the second dictionary.我想获取与第一个字典对应的值,但按照第二个字典的键顺序。 So the output should be like this:
所以输出应该是这样的:
dict3={'c':0,'b':1,'a':1,'d':0,'e':1,'g':1,'f':0}
Is there any way to do that?有没有办法做到这一点?
If you have you have Python 3.7+ you can use this:如果你有 Python 3.7+ 你可以使用这个:
dict1={'a':1,'b':1,'c':0,'d':0,'e':1,'f':0,'g':1}
dict2={'c':3,'b':2,'a':1,'d':1,'e':0,'g':0,'f':0}
dict3 = {k: dict1[k] for k in dict2.keys()}
print(dict3)
> {'c': 0, 'b': 1, 'a': 1, 'd': 0, 'e': 1, 'g': 1, 'f': 0}
What's New In Python 3.7 Python 3.7 中的新功能
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
dict 对象的插入顺序保留特性已被声明为 Python 语言规范的官方部分。
Is this what you meant?这是你的意思吗?
dict3 = {key:dict1[key] for key in dict2.keys()}
Tried on python 3.9.在 python 3.9 上试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.