8
votes

In the below shown dictionaries i want to check whether the key in aa matches the key in bb and also the value corresponding to it matches in bb or not.Is there a better way to write this code

  aa = {'a': 1, 'c': 3, 'b': 2}
  bb = {'a': 1, 'b': 2}

  for k in aa:
    if k in bb:
      if aa[k] == bb[k]:
         print "Key and value bot matches in aa and bb"
4
What is your desired result? Do you want a single Boolean value indicating whether all keys in aa that also appear in bb have matching values? Or one Boolean value per key? Or some code that prints "Key and value bot matches in aa and bb" once for each matching key/value pair? - Sven Marnach
Hmm... Overlooking the issue with the way you iterate over aa (hint, that's the same as aa.iterkeys()), your basic approach is actually just fine. What do you actually want to improve? - SingleNegationElimination
I somehow get the impression that everybody else seems to understand what Rajeev wants to do in the first place. Yet the answers to completely different things… - Sven Marnach

4 Answers

18
votes

Use sets to find all equivalents:

for (key, value) in set(aa.items()) & set(bb.items()):
    print '%s: %s is present in both aa and bb' % (key, value)

The & operator here gives you the intersection of both sets; alternatively you could write:

set(aa.items()).intersection(set(bb.items()))

Note that this does create full copies of both dicts so if these are very large you this may not be the best approach.

A shortcut would be to only test the keys:

for key in set(aa) & set(bb):
    if aa[key] == bb[key]:
        print '%s: %s is present in both aa and bb' % (key, value)

Here you only copy the keys of each dict to reduce the memory footprint.

When using Python 2.7, the dict type includes additional methods to create the required sets directly:

for (key, value) in aa.viewitems() & bb.viewitems():
    print '%s: %s is present in both aa and bb' % (key, value)

These are technically dictionary views but for the purposes of this problem they act the same.

5
votes

This can be written as one-liner with all:

all(bb[k] == v for k, v in aa.iteritems() if k in bb)

It's also more declarative approach, which might convey the intent better.

2
votes

If you want to iterate over all matching key/value pairs, you can use

for key, value in aa.viewitems() & bb.viewitems():
    ...

(Python 2.7)

0
votes
aa = {'a': 1, 'c': 3, 'b': 2}
bb = {'a': 1, 'b': 2}

[k for k,v in aa.items() if k in bb]

['a', 'b']

Python 3