Search for matching key-value pairs of two dictionaries

What would be the most effective way to check if a pair of keywords from one dictionary exist in another dictionary.
Suppose if I have two dictionaries: dict1 and dict2 , and these two dictionaries have some common key value pairs. I want to find them and print them. What would be the most efficient way to do this? Please suggest.

+3
source share
3 answers

one way:

d_inter = dict([k, v for k, v in dict1.iteritems() if k in dict2 and dict2[k] == v])

other:

d_inter = dict(set(d1.iteritems()).intersection(d2.iteritems()))

I'm not sure which one would be more efficient, so compare both of them:

1. Solution with iteration through dicts:

  • we analyze all dict1 keys: for k,v in dict1.iteritems()O(n)
  • , dict2, if k in dict2 and dict2[k] == v → O (m)

O(n+m)O(n)

2. set s:

, a dict O(n):

  • d1 set(d1.iteritems())O(n)
  • d2 set(d2.iteritems())O(m)
  • O(min(len(s), len(t)), O(n * m)

O(2n*n*m), O (n^3) dicts: 1.

, a dict O(1) ( )

O(min(n,m)), - O(n*m), # 1 , # 2 , O(n+m) > O(min(n,m)).

, , , , !; -)

N.B.: set().

N.B.2: # 1 dict dict2, # 2 dict dict1.


N.B.2016: python2. python3 :

  • iteritems() items();
  • : {[k, v for … == v]};
  • as d.items() dict_items, , frozenset() {frozenset(d1.items()).intersection(d2.items())}.
+8

, - , :

if all([testKey in dict1, testKey in dict2]) and dict1[testKey] == dict2[testKey]:

KeyError, and (, , , )

, , :

for testKey in set(dict1.keys() + dict2.keys()):
    if all([testKey in dict1, testKey in dict2]) and dict1[testKey] == dict2[testKey]:
        commonDict[testKey] = dict1[testKey]
0

What about...

matching_dict_values = {}
for key in dict1.keys():
    if key in dict2.keys():
        if dict1[key] == dict2[key]:
            matching_dict_values[key]=dict1[key]
0
source

All Articles