gpt4 book ai didi

python - 如何使用 Python 比较来自同一字典键的嵌套字典值

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:38 26 4
gpt4 key购买 nike

我有两个字典 Content_11Content_05,在字典里面我有我需要比较的每个文件的校验和,如果校验和匹配打印类似成功的东西否则失败对于那个文件名。以下是我的数据结构,下面是我的代码片段。

Content_11 = {
"controls": {
"windows-library-1234.zip": "A123455adfasfasdfasdf", # SHA 256 checksum
"unix-library-1234.zip": "a2343dfasdfasdfasdfasdfasdfasdf"
},
"policies": {
"oracle-1234.zip": "A123455adfasfasdfasdfad",
"rhel7-1234.zip": "sdaf23234234234asdf",
}
}

Content_05 = {
"controls": {
"windows-library-1234.zip": "A123455adfasfasdfasdf",
"unix-library-1234.zip": "a2343dfasdfasdfasdfasdfasdfasdf"
},
"policies": {
"oracle-1234.zip": "A123455adfasfasdfasdfad",
"rhel7-1234.zip": "sdaf23234234234asdf",
}
}

我查看了一些来自 stackoverflow 的问题,但没有找到与我相关的问题。任何建议或改进表示赞赏。

for key_05, value_05 in Content_05.items():  # iterating inside content_05 dict
for key_05_1, value_05_1 in value_05.items(): # iterating inside the content_05 value for getting nested dict
for key_011, value_011 in Content_11.items(): # iterating insde content_11 dict for comparison
for key_11_1, value_11_1 in value_011.items():
if key_05 == key_011:
if value_05_1 == value_11_1:
print "Key {} and its value is {} is matching with {} and hence Success".format(key_05_1,
value_05_1,
value_11_1)
else:
print "Key {} and its value is {} is not matching with {} and hence FAILURE".format(key_05_1,
value_05_1,
value_11_1)

最佳答案

你做的工作太多了;无需遍历两个词典,因为您可以只测试其中一个词典中的键是否在另一个词典中可用。

您可以使用 dict.get() 返回默认值并进一步简化测试;默认情况下 dict.get() 为缺失值返回 None,只需在比较中使用它:

for type_, checksums in Content_05.items():
# type_ is assumed to be present in the other dictionary
other_checksums = Content_11[type_]

for filename, hash in checksums.items():
other_hash = other_checksums.get(filename)
if hash != other_hash:
print("Failure: Checksum mismatch for {}, expected {}, got {}".format(
filename, hash, other_hash))
else:
print("Success: {} checksum matched".format(filename))

我也尝试使用更易读的变量名;文件名、校验和和哈希比 key_05_1 等更容易理解。

关于python - 如何使用 Python 比较来自同一字典键的嵌套字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com