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
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]
© 2024 OneMinuteCode. All rights reserved.