简体   繁体   English

比较python中两个字典的最有效方法

[英]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.

相关问题 连接两个字典并按不同键对它们进行分组并汇总值的最有效方法 - Most efficient way to join two dictionaries and group them by different key and sum up values 比较两个熊猫数据框并根据条件更新一个数据框的最有效方法 - Most efficient way to compare two panda data frame and update one dataframe based on condition 将复杂的字典列表转换为 Pandas Dataframe 的最有效方法 - Most Efficient Way to Convert a Complex List of Dictionaries Into a Pandas Dataframe 编辑字典列表中的值的最有效方法是什么? - What is the most efficient way to edit the values in a list of dictionaries? 比较Python中两个字典之间的整数值 - Compare integer values between two dictionaries in Python 比较两组的最有效方法是什么? - What is the most efficient way of comparing two sets? python 中是否有更好的方法来比较不同列表中的字典? - Is there a better way in python to compare dictionaries in different list? 比较和过滤python中的两个嵌套字典 - compare and filter the two nested dictionaries in python 比较Python中2个字符串的最有效方法是什么 - What is the most efficient way of comparring 2 strings in Python 在 python 中查找邻居的最有效方法 - Most efficient way to find neighbors of neighbors in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM