Membership operator in Nested Dictionary

Viewed 33

I have been trying to create a login system using a nested dictionary. The first dictionary contains the key as user_type and value as another dictionary of the key as user_name and value as a password. I wanted to check whether a username exists in a dictionary that is nested. I have been facing some errors.

Traceback (most recent call last):
  File "main.py", line 130, in <module>
    if uname in user.values().keys():
AttributeError: 'dict_values' object has no attribute 'keys'

My code is

user = {
  "admin" : {"alex" : "1234", "phil" : "3453", "peter" : "23423", "lucas" : "12133"},
  "student" : {"tanishk" : "23423", "sanskar" : "7445", "shashwat" : "5573", "ayush" : "96456"}
}

uname = input("Enter your username : ").lower()

if uname in user.values().keys():
  print("Hello")

1 Answers

Mechanic Pig's comment gives the answer.

if any(uname in mp for mp in user.values())

Here is the explanation:

user.values() returns a sequence of values of all items in the outer dictionary. Something like:

[
  {"alex": "1234", "phil": "3453", "peter": "23423", "lucas": "12133"},
  {"tanishk": "23423", "sanskar": "7445", "shashwat": "5573", "ayush": "96456"},
]

It is just not a list, but a 'dict_values' object, but it works similarly like a list. This object has no method .keys() so that's why you get the AttributeError. You can, however, iterate over the dictionaries within this object and ask, whether any of those (inner) dictionaries has given key. The built-in function any() does that for you, but it is similar to:

for inner_dictionary in user.values():
    if uname in inner_dictionary.keys():
        print('Hello!')
        break
Related