在Python中,如何检查另一个dict中值的键值(在一个dict中定义)? [英] How to check for presence of the key of a value (as defined in one dict) in another dict, in Python?

查看:342
本文介绍了在Python中,如何检查另一个dict中值的键值(在一个dict中定义)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定映射命令映射

  {
'John':'A',
'Mary':'B',
'Tim':'C'
}
pre>

然后我提供了一个dict 支出

  {
'John':23,
'Mary':1,
}
pre>

和一个dict 收入

  {
'A':12,
'B':2,
'C':23
}

然后:

  for k ,v in spend.items():
#do stuff

在此循环中,我要检查 收入中的条目是否在支出中没有相应的条目 (基于我们的映射)。一个这样的例子是Tim(因为'C'存在于收入中,但'Tim'不存在于支出 )。



再次循环一个方法(在循环) - 这次超过收入.keys(),并检查该键不在中花费.keys() - 不幸的是,这不会导致 len(收入)每次匹配的重复次数。



我们如何在没有循环的情况下实现所需的反向检查? / p>

解决方案

如果您在映射中反转键值和/或code>字典,然后循环收入。在执行循环之前,您不需要永久反转它,只需将其反转并存储在新的字典中。



示例 -

  reversemapping = {v:k for k,v in mapping.items()} 
for k,v in revenue.items():
如果(k不是反向映射)或(反向映射[k]不支出):
print(k)


Given a mapping dict mapping:

{
'John': 'A',
'Mary': 'B',
'Tim' :'C'
}

I am then provided a dict spend:

{
'John': 23,
'Mary': 1,
}

and a dict revenue:

{
'A': 12,
'B': 2,
'C': 23
}

then:

for k, v in spend.items():
# do stuff

Within this loop, I want to check if an entry in revenue does not have a corresponding entry in spend (based on our mapping). One such example is Tim (because 'C' is present in revenue, but 'Tim' is not present in spend).

An approach of looping again (within this for loop) - this time over revenue.keys() and checking that the key is not in spend.keys() - unfortunately is not an option as this will result in len(revenue) number of duplicates, per match.

How do we achieve the desired reverse checking without a loop?

解决方案

You can do this easily if you reverse your keys and values in the mapping dictionary and then loop over revenue dicitonary. You do not need to permanently reverse it, just reverse it and store in a new dictionary before you do the loop.

Example -

reversedmapping = {v:k for k,v in mapping.items()}
for k,v in revenue.items():
    if (k not in reversedmapping) or (reversedmapping[k] not in spend):
        print(k)

这篇关于在Python中,如何检查另一个dict中值的键值(在一个dict中定义)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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