如何使用变量访问python字典中的键值? [英] How to access the key values in python dictionary with variables?

查看:725
本文介绍了如何使用变量访问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)])

这篇关于如何使用变量访问python字典中的键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆