从一个字典的键和另一个字典的值构建一个新字典 [英] Build a new dictionary from the keys of one dictionary and the values of another dictionary

查看:54
本文介绍了从一个字典的键和另一个字典的值构建一个新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典:

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

我想从 dict_1 中获取密钥,并从 dict_2 中获取值并制作一个新的 dict_3

I want to take the keys from dict_1 and values from dict_2 and make a new dict_3

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

推荐答案

使用正则字典无法以任何可预测的方式来完成您要尝试的操作.正如@PadraicCunningham和其他人已经在评论中指出的那样,词典的顺序是任意的.

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.

如果您仍然想获得结果,则必须从头开始使用有序词典.

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)])

这篇关于从一个字典的键和另一个字典的值构建一个新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆