2

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?

Pyderman
  • 14,809
  • 13
  • 61
  • 106
  • for clarification: the `mapping` dict is static. The `spend` and `mapping` dicts will each day contain differing data. – Pyderman Jul 07 '15 at 05:44
  • 1
    Do you have to loop through spend? If you can loop through mapping then it can be done in one line: [k for k,v in mapping.items() if not spend.get(k) and revenue.get(v)] – logee Jul 07 '15 at 05:55

1 Answers1

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)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Nicely done, Anand. It's working well, but now I have to test that **both** conditions are true, and I'm encountering the is problem. Any thoughts? http://stackoverflow.com/questions/31331029/why-does-a-keyerror-get-thrown-in-logical-and-but-not-in-a-logical-or#31331059 – Pyderman Jul 10 '15 at 02:05
  • 1
    So do you want to not print `k` when a `key` in revenue dict is not found as a value in `mapping`? – Anand S Kumar Jul 10 '15 at 02:10