如何检查python字典中是否存在值?

假设我的字典字典叫做记录是这样的,其中第一、第二等是键


 records = {

                 first: {

                    "email": email,

                    "password": password,

                    "pwd_secret" : None

                     }


                 second: {

                    "email": email,

                    "password": password,

                    "pwd_secret" : code

                     }

           }

然后我检查代码是否等于pwd_secret任何字典中“”的值。该功能的代码可以完美运行,但是我的 else 语句不起作用(如果代码不是pwd_secret任何字典中“”的值,那么我想引发错误。但是目前即使代码存在,它也只会引发错误。) 有什么建议么?


 for k, v in records.items():

                pwd_secret = v.get('pwd_secret')

                if pwd_secret == code:

                    hashed_password = hash_password(new_password)

                    v['password'] = hashed_password

                #else:

                    #raise ValueError("code is invalid")


鸿蒙传说
浏览 81回答 3
3回答

四季花海

您可以通过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")

皈依舞

功能: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

哔哔one

假设这本字典: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()子句,只需放置您希望执行的必要操作。换句话说-您的代码应该可以工作,问题可能不在于在嵌套字典中查找值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python