简体   繁体   中英

compare two dictionaries key by key

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.

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}}

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM