如何在 python 中使用 f 字符串将变量用作字典键?

How to use a variable as dictionary key using f-string in python?

我正在尝试打印字典的字典项值,但我的项也是另一个用户输入变量。如何使用 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}"]}')
# Following part is working!!!
print(f'Youve selected {languages[option]}')

您需要使用下一个字符串:print(f'Youve selected {languages[option]}')

f-string 不允许嵌套插值。但是,要从字典中获取正确的选项,您不需要引号,languages[option] 即可。

因此您要使用的线路将是 print(f"You've selected {languages[option]}")

option 是一个变量,但是你做的option 是一个字符串。这意味着你给字典语言的键在你的情况下是{option}而这个键不存在

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]}')

您没有使用变量 option,您将 {option} 用作字符串并尝试打印键 {option} 的值。只需删除括号和“”。

您也可以在 f 字符串中使用 f 字符串,但这不是必需的。

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

您的代码之所以不起作用,是因为您在 f 字符串中创建了一个字符串,而不是在 f 字符串中创建了一个 f 字符串