如何使用变量访问python字典中的键值?
问题描述:
我有一个字典,其键是数字.看起来像这样:
I have a dict whose keys are numbers. It looks like this:
{'1': 3, '2': 7, '3', 14}
我需要使用变量访问每个键的值,但是由于键的引号而被卡住.我该怎么办?
I need to access the value of each key with a variable, but get stuck because of the quotation marks of keys. How can I do that?
答
您可以将数字转换为字符串,
You can cast your number to a string,
my_dict = {'1': 3, '2': 7, '3': 14}
number = 2
print(my_dict[str(number)])