有没有更好的方法来比较字典值 [英] Is there a better way to compare dictionary values

查看:27
本文介绍了有没有更好的方法来比较字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下函数来比较字典值并显示所有不匹配的值.有没有更快或更好的方法?

I am currently using the following function to compare dictionary values and display all the values that don't match. Is there a faster or better way to do it?

match = True
for keys in dict1:
    if dict1[keys] != dict2[keys]:
        match = False
        print keys
        print dict1[keys],
        print  '->' ,
        print dict2[keys]

两个字典都包含相同的键.

Both the dicts contain the same keys.

推荐答案

如果 dicts 具有相同的键集,并且您需要所有这些打印来解决任何值差异,那么您无能为力;也许是这样的:

If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:

diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
  print k, ':', dict1[k], '->', dict2[k]

几乎等同于您拥有的内容,但您可能会获得更好的演示,例如在循环之前对差异键进行排序.

pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.

这篇关于有没有更好的方法来比较字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆