简体   繁体   中英

diff in a nested python dictionary

I have two dictionary and i want to find the difference of the two dictionary.The dictionary is a nested and the format is below:

d1 = { '1/1':{'Packets received':10,'Packets lost':4000},'2/2':{'Packets received':100,'Packets lost':500},'3/3':{'Packets received':20,'Packets lost':400}}
d2 = { '2/2':{'Packets received':100,'Packets lost':600},'1/1':{'Packets received':10,'Packets lost':4000},'3/3':{'Packets received':20,'Packets lost':400}}

The dictionary has the port counter details which I have populated from a file. The keys are same for both the dictionary. The objective is to loop through the inner dictionary and see if the value is same in both the dictionary(value of the inner dictionary).If there is an difference(that is the second is greater than the first) then I need to populate it in another dictionary so that I can iterate over it and print it.

For example:

d3_diff = { '2/2':{'Packets received':100,'Packets lost':100}}

Else I want to directly print something like below directly,

Let's say 'Packets lost' value has incremented in 2/2,then I want to print:

"Port 2/2 has experienced some packet loss(100).please check"

There were some solutions to loop through nested dictionary already but I couldn't make it to work for my requirement.

Here is the code to find key-value pairs where d2[key][packet lost] is greater than its corresponding value in d1.

d1 = { '1/1':{'Packets received':10,'Packets lost':4000},'2/2':{'Packets received':100,'Packets lost':500},'3/3':{'Packets received':20,'Packets lost':400}}
d2 = { '2/2':{'Packets received':100,'Packets lost':600},'1/1':{'Packets received':10,'Packets lost':4000},'3/3':{'Packets received':20,'Packets lost':400}}

d3 = {}
for k, v in d2.items():
    if d2[k]['Packets lost'] > d1[k]['Packets lost']:
        d3[k] = v

print(d3.items())

output:

dict_items([('2/2', {'Packets lost': 600, 'Packets received': 100})])

You can now loop through d3 for whatever reasons you want and print the relevant messages.

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