To find a key with a value in the dictionary...?

Asked 2 years ago, Updated 2 years ago, 140 views

You want to find a name by age in a dictionary that stores a key-value pair with a name as key and an age as value.

I can compare ages or find values, but I don't know how to access keys.

list = {'george':16,'amber':19}
search_age = raw_input ("Please enter a name")
for age in list.values():
    if age == search_age:
        name = list[age] #Problem here
        print name

dictionary python

2022-09-22 22:12

1 Answers

You must write dict.items().

for name, age in mydict.items(): Access items one by one in #mydict, and save key and value in name and age, respectively
    if age == search_age:
        print name

If you want to make it shorter, you can do this

[name for name, age in mydict.items() if age == search_age]


2022-09-22 22:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.