How to check for presence of the key of a value (a

2019-07-10 07:14发布

问题:

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)