+ 1

list data inside dict

user_input = input() my_dict = {1: ["Agatha", "Christie"], 2: ["Bob", "Dylan"]} # how to retrieve only Bob Dylan's first name from this dict?

1st Apr 2021, 6:19 PM
Thomas Zufferey
6 Respuestas
+ 3
last_name = "Dylan" for i in my_dict.values(): if i[1] == last_name: first_name = i[0] break print(first_name)
1st Apr 2021, 6:26 PM
Russ
Russ - avatar
+ 3
You 1st access the list you want in the dict using the key. This will return the value associated with that key. In this case a list. You can then use the index or other list methods on the list as normal. lst = my_dict[2] name = lst[0] # 'Bob's Or name = my_dict[2][0] These are a couple of options there are a few other ways as well, depending on what you need, want.
1st Apr 2021, 6:31 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
print(my_dict[2][0]) should work. Or whats the user input for?
1st Apr 2021, 6:32 PM
Alexander Crum
Alexander Crum - avatar
+ 1
Thank you all a lot for your help PS : input() was for user to input a name. If the name is in the dict, my program prints the related email, otherwise "Not found". It's originaléy the challenge "Fuzzy Search" in the Python Core Course.
1st Apr 2021, 7:29 PM
Thomas Zufferey
0
"If the name is in the dict, my program prints the related email, otherwise "Not found"." Where is e-mail address? there's no e-mail address in <my_dict>.
2nd Apr 2021, 8:30 AM
Ipang
0
Ipang I think he was just using these names as examples for his question
2nd Apr 2021, 9:03 AM
Alexander Crum
Alexander Crum - avatar