将Python字典的值替换为与其他字典键匹配的另一个字典的值 [英] Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key

查看:734
本文介绍了将Python字典的值替换为与其他字典键匹配的另一个字典的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有两个字典

dictionary1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dictionary2 = {'value1': 'AAA', 'value3': 'CCC'}

我想用dictionary2的值替换dictionary1的值,上面的示例将产生以下输出

I want to replace the values of dictionary1 with the values from dictionary2 which with the example above would produce the following output

{'key1': 'AAA', 'key2': 'value2', 'key3': 'CCC'}

在其他示例中,我认为应该以如下方式开始代码:

From other examples I have read I think that I should begin my code as follows:

for key, value in dictionary1.iteritems():
    if value ==

现在,我不确定在另一本字典中循环查找以发现Dictionary1中的值是否与Dictionary2中的键匹配的最佳方法.

Now I am unsure as to the best method to cycle through the other dictionary to find if the value from dictionary1 matches a key from dictionary2.

推荐答案

您可以使用字典理解来做到这一点

You can do this with dictionary comprehension, like this

>>> dictionary1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
>>> dictionary2 = {'value1': 'AAA', 'value3': 'CCC'}
>>> {k: dictionary2.get(v, v) for k, v in dictionary1.items()}
{'key3': 'CCC', 'key2': 'value2', 'key1': 'AAA'}

在这里,dict2.get(v, v)将尝试从dict2获取与值v相对应的值.如果找不到,则会返回默认值(第二个参数)v本身.

Here, dict2.get(v, v) will try to get the value corresponding to the value v from dict2. If it is not found, the default value (second parameter), v itself will be returned.

注释1:您所遇到的问题称为字典,而不是列表.

Note 1: What you have in question, are called dictionaries, not lists.

注2::如果您使用的是Python 2.7,则可能要使用dict1.iteritemsdict1.viewitems而不是dict1.items.在此答案中详细举例说明了原因.

Note 2: If you are using Python 2.7, then you might want to use dict1.iteritems or dict1.viewitems instead of dict1.items. The reason is explained, elaborately, with examples, in this answer.

这篇关于将Python字典的值替换为与其他字典键匹配的另一个字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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