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

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

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

我猜,你真正想要的是,在 n 个不同的字典之间select。

Eval 当然可以,但风格不佳且性能不佳。

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

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

您可以在 MasterDict 中放入任意数量的口述。

访问一个:

MasterDict[iWantTheDictName]['range']