简体   繁体   中英

How to get a dictionary name from a list in python

I am new to python and stack exchange. thanks for your help. I have a list of names of dictionaries and would like to iterate over the list and retrieve values from the dictionaries.

my code

#!/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']

the output

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

The desired result is that:

 iWantTheDictName == game50and25['range']

I guess, what you really want is, to select between n different dicts.

Eval would work of course, but would be bad style and have bad performance.

I would recommend a dict of dicts -- something like that:

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

You can put as many dicts into the MasterDict as you like.

To access one:

MasterDict[iWantTheDictName]['range']

Try using eval(iWantTheDictName)['range'] . The output will be [50, 25] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM