在Python中,如何检查另一个dict中值的键值(在一个dict中定义)? [英] How to check for presence of the key of a value (as defined in one dict) in another dict, in Python?
问题描述
给定映射命令映射
:
{
pre>
'John':'A',
'Mary':'B',
'Tim':'C'
}
然后我提供了一个dict
支出
:{
pre>
'John':23,
'Mary':1,
}
和一个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 inspend
(based on our mapping). One such example is Tim (because 'C' is present inrevenue
, but 'Tim' is not present inspend
).An approach of looping again (within this
for
loop) - this time overrevenue.keys()
and checking that the key is not inspend.keys()
- unfortunately is not an option as this will result inlen(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屋!