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