top of page

Python Programming Help

Public·2 members

Finding matching keys in two dictionaries - python

Given two dictionaries dic1 and dic2 which may contain some common keys, find the matching of keys in given dictionaries.


This way to find their intersection is very slow:

dic1 = {1: 4.5, 2: 3.0, 3: 1.5}
dic2 = {1: 3.5, 3: 4.5, 4: 1.0, 5: 2.5}

dict1Set = set(dic1)
dict2Set = set(dic2)

for id in dict1Set.intersection(dict2Set):
    print(id)

1

3


And here’s a good way that is simple and fast:


intersect = []
dic1 = {1: 4.5, 2: 3.0, 3: 1.5}
dic2 = {1: 3.5, 3: 4.5, 4: 1.0, 5: 2.5} 

for item in dic1.keys(  ):
    if dic2.has_key(item):
        intersect.append(item)
pr("Intersects:", intersect)

16 Views
bottom of page