-1

I'm trying to print dictionary item value of a dictionary but my item is also an another user input variable. How can I print the selected value with f-string?

option = ''
languages = {'1':'Learn Python', '2':'Learn Java', '3':'Learn C++', '4':'Learn PHP', '5':'Quit'}
option = input('Please choose an option between 1 and 5')

# Following part is not working!!!
print(f'Youve selected {languages["{option}"]}')
dreftymac
  • 31,404
  • 26
  • 119
  • 182

4 Answers4

5
# Following part is working!!!
print(f'Youve selected {languages[option]}')
Darcy
  • 160
  • 1
  • 9
  • Yep thanks i think my mistake was to test the variable with a constant like option = 1 but forgot to change it into str() Thank you – Atilla Atǝş Jul 21 '21 at 10:41
0

You need use the next code:

option = input('Please choose an option between 1 and 5')
languages = {'1':'Learn Python', '2':'Learn Java', '3':'Learn C++', '4':'Learn PHP', '5':'Quit'}

print(f'Youve selected {languages[option]}')
m3r1v3
  • 362
  • 5
  • 19
0

f-string don't not allow nested interpolation. However, to get the correct option from the dictionary you don't need quotes, languages[option] will do.

So the line you are looking to use will be print(f"You've selected {languages[option]}")

0

option is a variable, but you made option to a string. That means the key you gave the dictionary language is in your case {option} and this key doesnt exist

languages = {'1':'Learn Python', '2':'Learn Java', '3':'Learn C++', '4':'Learn PHP', '5':'Quit'}
option = str(input('Please choose an option between 1 and 5'))

# Following part is  working!!!
print(f'Youve selected {languages[option]}')

You didnt use the variable option, you used {option} as a string and tried to print the value of the key {option}. Just remove the brackets and the "".

You could also use a f string in a f string, but thats not necessary.

print(f'Youve selected {languages[f"{option}"]}')

The reason, why your code didnt work is in that case, because you made a string in a f string and not a f string in a f string

TheEnd1278
  • 47
  • 4