I’m trying to get values from a nested dict via user input. The problem is that the nested dictionaries have generic names (d1,d1, etc.). The user inputs, say, last name and the program returns the email.
I know this is basic, so I apologize in advance. This is what I have so far.
my_dict = {
'd1':{
'fname':'john',
'lname':'doe',
'age':'26',
'email':'jdoe@mail.com'
},
'd2':{
'fname':'mary',
'lname':'jane',
'age':'32',
'email':'mjane@mail.com'
}
}
lname = input("enter last name: ")
for emp in my_dict.items():
print(emp)
Output:
enter last name: john
('d1', {'fname': 'john', 'lname': 'doe', 'age': '26', 'email': 'jdoe@mail.com'})
('d2', {'fname': 'mary', 'lname': 'jane', 'age': '32', 'email': 'mjane@mail.com'})
>Solution :
This is a function that takes a last name as input, then iterates over each dictionary (key, value) pair and returns the email as soon as there is a match:
def get_email_from_last_name(last_name):
for k, v in my_dict.items():
if v['lname'] == lname:
return v['email']
lname = input("enter last name: ")
email = get_email_from_last_name(lname)
print(email)
prints:
enter last name: doe
jdoe@mail.com