3 回答
TA贡献1811条经验 获得超5个赞
您可以通过values并使用if条件:
for v in records.values():
pwd_secret = v.get('pwd_secret')
if pwd_secret == code:
# found
你真的不需要经历,items因为看起来你不需要钥匙。
至于你的错误,是从分支ValueError中引发的,因为不等于. 如果您没有预料到这一点,那么您应该在编辑器中设置一个断点并逐行遍历您的代码以查看实际发生的情况。elsepwd_secretcode
另一个更简单的调试步骤是print找出每个值是什么:
for v in records.values():
pwd_secret = v.get('pwd_secret')
print(f"pwd secret: {pwd_secret} and code: {code}") # print values here
if pwd_secret == code:
print("Secret is valid!")
else:
raise ValueError("code is invalid")
如果在内部字典中找不到,这也可能会指出v.get('pwd_secret')给你默认值。None'pwd_secret'
此外,如果您想检查任何内部词典是否有代码,您可以使用内置函数any():
if any(v.get('pwd_secret') == code for v in records.values()):
print("Secret found!")
else:
raise ValueError("Secret not found")
TA贡献1851条经验 获得超3个赞
功能:
def check_value(dict_of_dicts, value):
return any(value in dict_.values() for dict_ in dict_of_dicts.values())
例子:
a = {
'first': {
"email": 'email',
"password": 'password',
"pwd_secret": None
},
'second': {
"email": 'email',
"password": 'password',
"pwd_secret": 'code'
}
}
check_value(a, 'code')
# True
TA贡献1854条经验 获得超8个赞
假设这本字典:
records = {
'first': {
"email": 1234,
"password": 1234,
"pwd_secret" : None
},
'second': {
"email": 1234,
"password": 1234,
"pwd_secret" : 'code'
}
}
和测试循环:
for v in records.values():
if v['pwd_secret'] == 'code':
print('here...')
而不是该print()子句,只需放置您希望执行的必要操作。换句话说-您的代码应该可以工作,问题可能不在于在嵌套字典中查找值。
添加回答
举报