python - 查找python中两个dict之间的不匹配(键和值)
问题描述
查找两个字典之间的不匹配(键和值)
superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4}
print(all(item in superset.items() for item in subset.items()))
# Expected output: True and desired output True
superset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
subset = {"a":1, "b": 2, "c": 3, "d":5}
print(all(item in superset.items() for item in subset.items()))
# Expected output: False and desired output False
在测试用例下面,因为我只检查两个字典之间不匹配的键和值,所以在超集或子集字典中将忽略额外的键和值。在下面的情况下,子集中包含“e”是键,5 是对应的值,相同的键或值不存在于超集中,因此我们可以忽略,因为它不是不匹配的。
superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(all(item in superset.items() for item in subset.items()))
# Expected output: True and desired output False
解决方案
If you want to ignore mismatching keys, just check keys that exists in both dicts:
superset = {"a":1, "b": 2, "c": 3, "d":4, "f":8}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(
all(
superset[key] == subset[key]
for key in set(superset.keys()) & set(subset.keys())
)
)
will print:
True
If you want to check that each dict contains no mismatched values from another, you should modify your code like this:
superset = {"a":1, "b": 2, "c": 3, "d":4, "f": 10, "g": 5}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(
all(
superset[key] == subset[key]
for key in set(superset.keys()) & set(subset.keys())
) and
all(
superset[key] not in subset.values()
for key in set(superset.keys()) - set(subset.keys())
) and
all(
subset[key] not in superset.values()
for key in set(subset.keys()) - set(superset.keys())
)
)
will print:
False
推荐阅读
- database - 分片后我的 mongodb 数据库大小增加了一倍?
- ruby-on-rails - Docker 和 Rails:无法访问日志文件
- scala - 无法重新启动从 Http 响应创建的 akka 源
- reactjs - 如何使用 next-i18next 将 i18n 或 t 函数传递给依赖项
- c++ - 在链表节点中分配数组
- mysql - google cloud sql——mysql导入问题
- python - 格式化日期列 pandas
- flutter - 即使在使用 Expanded 后出现“RenderBox 未布局”错误
- html - 模态窗口的 CSS 宽度和高度
- python - 为什么我不能用 python 中的字典值做数学运算?