简体   繁体   中英

Most efficient way to compare two dictionaries in python

dic1 = {'memory':'4','cpu':'2','disk':{'total':'160','swap':'4','/':'26','/var':'7','/tmp':'2'}}

dic2 = {'memory':8','cpu':'2','disk':{'total':'120,'swap':'4','/':'26','/var':'7','/tmp':'2'}}

Please note that both dictionaries itself contains another dictionary. What is the most efficient way to compare each items without doing dict1==dict2 ?

Since i have to see some % change in values. So the only option left is iterating thru each dictionary items. something like:

for key1 in dic1:
   for key2 in dic2:
      if not isinstance(dic1[key1],dict):
         #compare cpu & memory here
         if int(dic1[key1]) > int(dict2[key2])
      else:
          #compare disk(internal dictionary here)

You can use itertools.zip_longest to zip the values and compare them in a list comprehension :

>>> from itertools import chain,zip_longest

["do something" if isinstance(i,dict) and all(k<v for k,v in zip_longest(i.values(),j.values())) else "do something" for i,j in zip_longest(dic1.values(),dic2.values())]

Note that here based on your need you can use another function instead of all you may be interest to use any or maybe you want to to some arithmetic operation on the values.

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