Search code examples
pythonperformancecomparedefaultdict

Compare two defaultdictionaries Python


Is there a more efficient way to compare two dictionaries than a double loop ?

for i in d:
    for i2 in d2:
        if i == i2:
            key1 = d.get(i)
            key2 = d2.get(i2)
            print("First key:", key1)
            print("Second key:", key2)

Solution

  • You can get the intersection of the keys by using dictionary views. These operate as sets, meaning you can generate their intersection with &.

    Python 2:

    for key in d.viewkeys() & d2.viewkeys():
        value1 = d[key]
        value2 = d2[key]
    

    Python 3:

    for key in d.keys() & d2.keys():
        value1 = d[key]
        value2 = d2[key]
    

    Even if you didn't have dictionary views, you didn't need to use a double loop. All you needed to do was to test if the key was present:

    for key in d:
        if key in d2:
            value1 = d[key]
            value2 = d2[key]