[英]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 ?
在不执行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 : 您可以使用
itertools.zip_longest
压缩值,并在列表itertools.zip_longest
对它们进行比较:
>>> 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. 请注意,根据您的需要,您可以使用另一个函数而不是
all
您可能会对使用any
或可能要对值进行算术运算感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.