How to check for presence of the key of a value (as defined in one dict) in another dict, in Python?

回眸只為那壹抹淺笑 提交于 2019-12-11 03:48:46

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/31260579/how-to-check-for-presence-of-the-key-of-a-value-as-defined-in-one-dict-in-anot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!