Python:按键、值比较两个相同的字典

标签 python dictionary matching

我想比较两个字典的长度以及每个字典中每个键、值对的长度。如果在查找时没有匹配项,我还需要能够打印出来。

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

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]

如果第一个条件成立,第二个条件就没有意义了。尝试使用 代替:

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

关于Python:按键、值比较两个相同的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711549/

相关文章:

python - 正则表达式检测base64

python - 在 Pyspark rdd 中更改 saveAsTextFile 选项中的分隔符

python - 遍历字典并按顺序打印其值

字符串匹配算法

Javascript 和 Regex - 字符串中单词的严格匹配

以两个相似数字开头的 8 位数字的正则表达式?

python - 如何从 sqlalchemy 中的关系中获取列表的字典?

python - 为什么在从 numpy empty_like 构造时打印数据框会破坏 python

python - 从文件中读取列表,并将其转换为 Python 字典列表

c++ - 如何在不移动的情况下交换 map 元素?