Python 3.x 比较python中两个词典的最有效方法

Python 3.x 比较python中两个词典的最有效方法,python-3.x,Python 3.x,请注意,两个词典本身都包含另一个词典。 在不执行dict1==dict2的情况下,比较每个项目最有效的方法是什么 因为我必须看到一些%的值变化。因此,剩下的唯一选项是遍历每个字典项。比如: dic1 = {'memory':'4','cpu':'2','disk':{'total':'160','swap':'4','/':'26','/var':'7','/tmp':'2'}} dic2 = {'memory':8','cpu':'2','disk':{'total':'120,'swap'

请注意,两个词典本身都包含另一个词典。 在不执行dict1==dict2的情况下,比较每个项目最有效的方法是什么

因为我必须看到一些%的值变化。因此,剩下的唯一选项是遍历每个字典项。比如:

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

您可以使用
itertools.zip\u longest
压缩值并在列表中进行比较:

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)
>来自itertools进口链,邮编:

[“做点什么”如果是instance(i,dict)和all(k您可以使用
itertools.zip\u longest
压缩值并在列表中进行比较:

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)
>来自itertools进口链,邮编:

如果“实例”(I,DICT)和所有(你想用KEY <代码> >磁盘> 和它的值是一个字典,“同样做某事”,同样,我需要看到“磁盘”字典中的值的%变化。是的,你可以认为字典和“磁盘”字典中的“键”都是相同的。它的值是字典吗?同样,我需要看到“磁盘”字典中的值的%变化。是的,你可以认为字典和“磁盘”中的“键”仍然相同。字典。我也想比较嵌套的字典值。有兴趣了解chain&zip_longest。希望这能用于改进perfomrance@akhi由于您没有提供如何处理该值,我建议使用一种通用方法。请检查编辑!我也想比较嵌套字典值。了解chain&z很有趣ip_最长。希望这是用于改进perfomrance@akhi因为你没有提供你想用这些值做什么,我建议你用一个通用的方法。检查编辑!