compare two dictionaries key by key

Question:

I have two python dictionaries like below :

d1 ={'k1':{'a':100}, 'k2':{'b':200}, 'k3':{'b':300}, 'k4':{'c':400}}
d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}

I want to compare same keys and find out the difference like below:

{'k1':{'diff':1}, 'k2':{'diff':0}, 'k3':{'diff':2}, 'k4':{'diff':1}}

This is guaranteed that both of the input dictionaries have same keys.

Asked By: soumya-kole

||

Answers:

source:

d1 = {'k1': {'a': 100}, 'k2': {'b': 200}, 'k3': {'b': 300}, 'k4': {'c': 400}}
d2 = {'k1': {'a': 101}, 'k2': {'b': 200}, 'k3': {'b': 302}, 'k4': {'c': 399}}

d3 = {}
for k in d1:
    d_tmp = {
        "diff": abs(list(d1[k].values())[0] - list(d2[k].values())[0])
    }
    d3[k] = d_tmp

print(d3)

output:

{'k1': {'diff': 1}, 'k2': {'diff': 0}, 'k3': {'diff': 2}, 'k4': {'diff': 1}}
Answered By: veekxt

You could perform something similar to this, where you iterate over all the keys in d1 and check their corresponding values in d2. You need a second inner loop that is responsible for comparing the appropriate inner key.

d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}

output = {}
for k, v in d1.items():
    for k2, v2 in v.items():
        output[k] = {'diff': abs(d2[k][k2] - v2)}
Answered By: DeveloperRyan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.