Keyword values ​​in python dictionary in two dictionaries

In the dictionaries below, I want to check if the key in aa matches the key in bb, and the corresponding value matches bb or not.Is there is 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"
+7
source share
4 answers

Use all equivalents to search:

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

The operator &gives you the intersection of both sets ; you can also write:

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

Please note that this creates full copies of both dicts, so if they are very large, you may not be the best approach.

The shortcut would only need to verify 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 amount of memory.

Python 2.7 dict :

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

, .

+16

all:

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

, .

+5

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

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

(Python 2.7)

+2
source
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

0
source

All Articles