我有两个字典,我想比较主机词典中的 srvuuid 和备份中的 srvuuidorg 字典。
这是主持人:
hosts = {}
for d in data['servers']['server']:
srvhostname = d['hostname']
srvuuid = d['uuid']
hosts[srvhostname] = srvuuid
这是备份:
backup = {}
for u in backup_list['storages']['storage']:
srvuuidorg = u['origin']
backup_status = u['state']
backup[srvuuidorg] = backup_status
我提取计算机主机名,然后检查该主机名是否存在于 hosts 词典中,并使用 srvuuid
获取输出hostname = gethostname()
print(hostname)
for srvhostname in hosts:
if srvhostname != hostname:
continue
if srvhostname == hostname:
print(srvhostname + " : " + hosts[srvhostname])
break
else:
print("There is no matching hostname or uuid.")
最后,我想比较 srvuuid 和 srvuuidorg 。下面的代码不起作用,这意味着执行时没有输出:
for srvuuidorg in backup:
if srvuuidorg != srvuuid:
continue
if srvuuidorg == srvuuid:
print("Status for " + srvuuidorg + " is " + backup_status)
break
else:
print("No maching uuid found.")
我应该如何比较这本词典中的两个值,或者应该更改主题的方法并使用与比较词典不同的方式?
答案 0 :(得分:1)
我认为您可能想要的是:
srvuuid_match = False
for srvuuidorg in backup:
if srvuuidorg == srvuuid:
print("Status for " + srvuuidorg + " is " + backup[srvuuidorg])
srvuuid_match = True
break
if srvuuid_match is False:
print("No maching uuid found.")
这将打印备份字典的srvuuidorg键上存储的值。我认为您遇到的问题是您使用的是先前代码块中的旧的backup_status值,而不是存储在backup [srvuuidorg] dict和密钥上的backup_status的正确值。
但是,没有必要循环。您可以这样做:
if srvuuid in backup:
print("Status for " + srvuuidorg + " is " + backup[srvuuid])
else:
print("No maching uuid found.")
如果srvuuidorg == srvuuid(即备份字典中存在srvuuid键),这将打印备份字典中srvuuid键上存储的值。那可能是一个更好的方法。希望有帮助!
答案 1 :(得分:0)
您无需遍历字典即可查看是否存在密钥,查找时间为O(1)
:
hostname = gethostname()
print(hostname)
if hostname in hosts:
print(srvhostname + " : " + hosts[hostname])
#srvuuid = hosts[hostname] ## I'm just guessing here
else:
print("There is no matching hostname or uuid.")
if srvuuid in backup:
print("Status for " + backup[srvuuid] + " is " + backup_status)
else:
print("No maching uuid found.")