简体   繁体   English

从一个字典的键和另一个字典的值构建一个新字典

[英]Build a new dictionary from the keys of one dictionary and the values of another dictionary

I have two dictionaries:我有两本词典:

dict_1 = ({'a':1, 'b':2,'c':3})
dict_2 = ({'x':4,'y':5,'z':6})

I want to take the keys from dict_1 and values from dict_2 and make a new dict_3我想从dict_1获取键和从dict_2 dict_1值并创建一个新的dict_3

dict_3 = ({'a':4,'b':5,'c':6})

What you are trying to do is impossible to do in any predictable way using regular dictionaries.您尝试做的事情是不可能使用常规词典以任何可预测的方式完成的。 As @PadraicCunningham and others have already pointed out in the comments, the order of dictionaries is arbitrary.正如@PadraicCunningham 和其他人已经在评论中指出的那样,字典的顺序是任意的。

If you still want to get your result, you must use ordered dictionaries from the start.如果您仍想获得结果,则必须从一开始就使用有序词典。

>>> from collections import OrderedDict
>>> d1 = OrderedDict((('a',1), ('b',2), ('c', 3)))
>>> d2 = OrderedDict((('x',4), ('y',5), ('z', 6)))
>>> d3 = OrderedDict(zip(d1.keys(), d2.values()))
>>> d3
OrderedDict([('a', 4), ('b', 5), ('c', 6)])

You can achieve this using zip and converting the resulting list to a dict :您可以使用zip并将结果列表转换为dict来实现此目的:

dict(zip(dict_1.keys(), dict_2.values()))

But since the dictionaries are unordered, it won't be identical to your expected result:但由于字典是无序的,它不会与您的预期结果相同:

{'a': 5, 'c': 4, 'b': 6}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用另一本词典中的键替换一个词典中的值 - Replacing values in one dictionary with the keys in another dictionary 通过比较来自另一本字典的键,从一本字典返回值 - Return values from one dictionary by comparing keys from another dictionary 用另一个字典的值替换一个字典的键以创建一个新的字典 - Replacing the keys of a dictionary with values of another dictionary to create a new dictionary 从另一个字典的值替换字典键 - Replace dictionary keys from values of another dictionary 将字典中的值作为键插入另一个字典 - Inserting values from a dictionary as keys in another dictionary 从一个字典的键和另一个字典 python 的对应值创建字典 - Create a dictionary from the keys of one dictionary and corresponding values of another dictionary python 如何通过修改特定值从另一个字典创建新字典(将两个键的值合二为一) - How to create a new dictionary from another one by modifying specific values (join the values of two keys into one) 将一个字典中的值与另一个字典中的键链接起来,并使用正则表达式在字符串中将一个替换为另一个 - Link values from one dictionary with keys from another dictionary and replace one for another within a string with regex Python根据键列表构建一个字典,并列出值列表 - Python build one dictionary from a list of keys, and a list of lists of values 将一本词典的键与另一本词典的键与值列表进行比较 - Comparing keys of one dictionary to another dictionary with a list of values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM