Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
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.
6 Answers
+ 3
psw = data.get(key)[1]
# or without loop:
psw = data.get(site,(None,None))[1]
+ 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)
+ 2
Okay, it is clearer now. Thank you all!
+ 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?
+ 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
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 ;)