简体   繁体   English

通过比较来自另一本字典的键,从一本字典返回值

[英]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.

相关问题 从一个字典的键和另一个字典的值构建一个新字典 - Build a new dictionary from the keys of one dictionary and the values of another dictionary 比较一个字典中的值与Python中另一个字典中的值 - Comparing values in one dictionary with values from another dictionary in Python 将一本词典的键与另一本词典的键与值列表进行比较 - Comparing keys of one dictionary to another dictionary with a list of values 从另一个字典的值替换字典键 - Replace dictionary keys from values of another dictionary 将字典中的值作为键插入另一个字典 - Inserting values from a dictionary as keys in another dictionary 将一个字典中的值与另一个字典中的键链接起来,并使用正则表达式在字符串中将一个替换为另一个 - Link values from one dictionary with keys from another dictionary and replace one for another within a string with regex 从一个字典的键和另一个字典 python 的对应值创建字典 - Create a dictionary from the keys of one dictionary and corresponding values of another dictionary python 如何根据匹配键将一个字典中的值添加到另一个字典中? - How to add values from one dictionary to another based on matching keys? Python 使用相同的键将一个字典中的值附加到另一个字典 - Python appending values from one dictionary to another with the same keys 如何从 python 中的字典中返回键和值 - how to return keys and values from a dictionary in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM