0

How to get a value from a tuple when the tuple is a value of a dictionary?

Hi guys, I'm back again since I've got another None output. I'm trying to write a code that returns the password corresponding to a site. Here's my piece of code: data = {'facebook': ('facebook email', 'facebook password'), 'instagram': ('instagram email', 'instagram password'), 'yahoo mail': ('yahoo email', 'yahoo password')} site = input() for key in data: if site == key: psw = data.get(key[1]) # get the password, that stands at index 1 of the tuple print(psw) # output None Why is the output None? How can I print the second value of the tuple properly? P.S.: I cannot upload the file of the code, I'm sorry for that but the app doesn't work so you are supposed to copy and paste on your editor.

6th Jul 2021, 6:20 PM
Carola
Carola - avatar
7 odpowiedzi
+ 3
psw = data.get(key)[1] # or without loop: psw = data.get(site,(None,None))[1]
6th Jul 2021, 6:26 PM
visph
visph - avatar
+ 2
# with dictionary items data = {'facebook': ('facebook email', 'facebook password'), 'instagram': ('instagram email', 'instagram password'), 'yahoo mail': ('yahoo email', 'yahoo password')} site = input().strip() psw = '' for key, val in data.items(): if site == key: psw = val[1] print(psw)
6th Jul 2021, 6:33 PM
minirkk
minirkk - avatar
+ 2
Okay, it is clearer now. Thank you all!
6th Jul 2021, 6:42 PM
Carola
Carola - avatar
+ 1
Ohhh right! I forgot the parentheses order! That makes much more sense now hahahaha By the way, I don't get the None thing and how to treat it. It didn't lead me to an error, technically, but what does None mean in this context?
6th Jul 2021, 6:33 PM
Carola
Carola - avatar
+ 1
get takes as second argument a default value to return if key is not found... so if key do not exists, a tuple is returned in wich there can be retrieved None at index 1 None is null / undefined special value in Python
6th Jul 2021, 6:36 PM
visph
visph - avatar
0
your loop code will throw an error if key not exist, as you will try to print a variable wich has not been assigned previously ;)
6th Jul 2021, 6:38 PM
visph
visph - avatar