[英]How to get a dictionary name from a list in python
我是python和堆栈交换的新手。 谢谢你的帮助。 我有一个字典名称的列表,想遍历该列表并从字典中检索值。
我的代码
#!/usr/bin/env python3
import sys
print(sys.version)
variations = ('game75and15', 'game56and46', 'game52and52', 'game50and36', 'game50and25')
game50and25 = {
'date': [1996,9,6],
'range': [50,25],
'arrayname': ['draw50and25']
}
print('this is variations[4] ',variations[4])
iWantTheDictName = variations[4]
print('this is iWantTheDictName ',iWantTheDictName)
print('this is game50and25[\'range\'] ',game50and25['range'])
thisDoesntWork = iWantTheDictName['range']
输出
3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2]
this is variations[4] game50and25
this is iWantTheDictName game50and25
this is game50and25['range'] [50, 25]
Traceback (most recent call last):
File "./tscript2", line 15, in <module>
thisDoesntWork = iWantTheDictName['range']
TypeError: string indices must be integers
理想的结果是:
iWantTheDictName == game50and25['range']
我想,您真正想要的是在n个不同的格中进行选择。
评估当然可以,但是风格会很差,性能也会很差。
我会推荐一个dict的命令-之类的东西:
MasterDict = {}
MasterDict['game50and25'] = {
'date': [1996,9,6],
'range': [50,25],
'arrayname': ['draw50and25']
}
您可以根据需要将尽可能多的字典放入MasterDict。
要访问一个:
MasterDict[iWantTheDictName]['range']
尝试使用eval(iWantTheDictName)['range']
。 输出将是[50, 25]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.