如何在python中从列表中获取词典名称

如何在python中从列表中获取词典名称,python,dictionary,Python,Dictionary,我不熟悉python和堆栈交换。谢谢你的帮助。我有一个字典的名称列表,希望遍历该列表并从字典中检索值 我的代码 #!/usr/bin/env python3 import sys print(sys.version) variations = ('game75and15', 'game56and46', 'game52and52', 'game50and36', 'game50and25') game50and25 = { 'date': [1996,9,6],

我不熟悉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

尝试使用evaliWantTheDictName['range']。输出将是[50,25]。

我想,您真正想要的是,在n个不同的dict之间进行选择

Eval当然会起作用,但风格不好,性能也不好

我想推荐一个dict of dicts-类似这样的东西:

MasterDict = {}
MasterDict['game50and25'] = {
    'date': [1996,9,6],
    'range': [50,25],
    'arrayname': ['draw50and25']
    }
你可以在MasterDict中放入任意数量的dict

要访问一个:

MasterDict[iWantTheDictName]['range']

成功了。谢谢因为我读到的东西,我一直害怕eval。我没有接受任何用户输入,我是从文件中接受输入,所以可能没问题?@RandyPerkins:您不需要使用eval。看看我的答案。Eval并不危险,只要你不把用户的输入放进去,但你还是应该避免它,因为它需要额外的计算能力。对于一个好的设计来说,这是不必要的。
MasterDict[iWantTheDictName]['range']