繁体   English   中英

Python:按键,值比较两个相同的词典

[英]Python: Compare two identical dictionaries by key, value

我想比较两个词典的长度以及每个词典中的每个键值对。 我还需要能够在寻找时打印出来。

我当前的代码似乎传递了长度标准,但在尝试匹配元素时失败:

assert_that(len(model_dict), len(server_dict))
    for x in model_dict:
        if x not in server_dict and model_dict[x] != server_dict[x]:
            print(x, model_dict[x])

server_dict字典中一个条目的示例:

{2847001:[[ - -94.8,28],[ - 95.4,28],[ - 96,28],[ - 96.5,28.1],[ - 96.667,28.133],[ - 97,28.2],[ - 97.6 ,28.3],[ - 98.3,28.4],[ - 98.9,28.6],[ - 99.4,29],[ - 99.8,29.5],[ - 100,30],[ - 100.1,30.5],[ - 100.2, 31]]]}

model_dict字典中一个条目的示例:

{2847001:[[ - 94.8,28],[ - 95.4,28],[ - 96,28],[ - 96.5,28.1],[ - 96.667,28.133],[ - 97,28.2],[ - 97.6, 28.3],[ - 98.3,28.4],[ - 98.9,28.6],[ - 99.4,29],[ - 99.8,29.5],[ - 100,30],[ - 100.1,30.5],[ - 100.2,31 ]]}

错误似乎在于使用and在条件中:

x not in server_dict and model_dict[x] != server_dict[x]

如果第一个条件通过,第二个条件没有意义。 尝试or改为:

x not in server_dict or model_dict[x] != server_dict[x] 

如果要检查每个键和值,可以使用dict.items和dict.get并使用默认值:

for k,v  in model_dict.items():
       if server_dict.get(k,object()) != v:
            print(k,v)

如果你只是想要任何dict中不同的键,你可以获得对称差异:

unique = model_dict.keys() ^ server_dict # viewkeys() python2

你需要or不是and 如果它不在server_dict ,您不想在那里检查它。

你过度了,这就是错误。 当你写这个

for x in model_dict:
    if x not in server_dict and model_dict[x] != server_dict[x]:
        print(x, model_dict[x])

对于model_dict每个键,您要检查在server_dict是否找不到相同的键,这本身就足够了。 你正在做什么and完全没有必要,而且不正确,因为你试图将model_dict中的键值与server_dict不存在的键值相匹配。

这样做:

{x: model_dict(x) for x in model_dict if x not in server_dict}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM