如何从python中的列表中获取字典名称

时间:2015-02-17 01:44:02

标签: python dictionary

我是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']

2 个答案:

答案 0 :(得分:3)

我想,你真正想要的是,在n个不同的词组之间进行选择。

当然,Eval会起作用,但风格会很糟糕并且表现不佳。

我会推荐一个dicts的词典 - 类似的东西:

MasterDict = {}
MasterDict['game50and25'] = {
    'date': [1996,9,6],
    'range': [50,25],
    'arrayname': ['draw50and25']
    }

您可以根据需要在MasterDict中添加尽可能多的词组。

要访问一个:

MasterDict[iWantTheDictName]['range']

答案 1 :(得分:2)

尝试使用eval(iWantTheDictName)['range']。输出将为[50, 25]