Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary match key values in two dictionaries

Tags:

python

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"
like image 387
Rajeev Avatar asked May 31 '12 11:05

Rajeev


People also ask

How do you compare keys and values of two dictionaries in python?

The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

How do you match two dictionaries in python?

Using == operator to Compare Two Dictionaries Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.

Can you use == on dictionaries in python?

According to the python doc, you can indeed use the == operator on dictionaries.

Can a dictionary have two keys with the same value two values with the same key?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


1 Answers

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.

like image 199
Martijn Pieters Avatar answered Sep 28 '22 18:09

Martijn Pieters