Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return value from nested dictionary in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading