在字典中找到匹配的关键字&用值替换键 [英] Find matching keys in dictionaries & replace keys with values

查看:36
本文介绍了在字典中找到匹配的关键字&用值替换键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典,我需要比较键,如果键匹配,则需要用第一个字典中的值替换第二个字典中的键.

I have two dictionaries and I need to compare the keys and if the keys match, I need to replace the second dictionary keys with the values from the first.

d1 = {'22': 'Jane', '33': 'Tom', '44': 'John', '55': 'Laura'}    
d2 = {'22': {'Lilly', 'Jake'}, '33' : {'Janet'}, '44': {'Tim'}}

我开始了,但是已经有些问题了...

I started, but something is already wrong...

for k, v in d2.items():
    d2[k] = d1(k, v)
    print(d2)

它应该看起来像这样:

{'Jane': {'Lilly', 'Jake'}, 'Tom': {'Janet'}, 'John': {'Tim'}}

推荐答案

您可以使用dict理解来迭代两个dict的键的交集并输出相应的值作为新dict的键和值:

You can use a dict comprehension that iterates over the set intersection of the keys of the two dicts and output the corresponding values as the keys and values of the new dict:

{d1[k]: d2[k] for k in d1.keys() & d2.keys()}

这将返回:

{'Tom': {'Janet'}, 'Jane': {'Jake', 'Lilly'}, 'John': {'Tim'}}

但是,集合是无序的.如果您想保留 d2 的键顺序(因为自python 3.7起就对键进行了排序),则可以遍历 d2 的项:

Sets are unordered, however. If you would like to preserve the key order of d2 (as keys are ordered since Python 3.7), you can iterate over the items of d2 instead:

{d1[k]: v for k, v in d2.items() if k in d1}

这将返回:

{'Jane': {'Lilly', 'Jake'}, 'Tom': {'Janet'}, 'John': {'Tim'}}

这篇关于在字典中找到匹配的关键字&用值替换键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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