0

Let this is content of .ini file with more similar dictionaries

[section]
cmd_list = {'gamess': "416.gamess/exe/gamess",
            'sjeng': '458.sjeng/exe/sjeng',
            'soplex': '450.soplex/exe/soplex',
            'astar': '473.astar/exe/astar',
           }             
...

now in my main file and want to access the dictionary dynamically:

for r in 'string'
     cmd_list[r][1] #from .ini
     cmd_list[r][0] #from .ini
    ....

how to do that?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

1

If you parsed the .ini file using the ConfigParser library, the value of cmd_list would still be a string containing a Python dict literal; it is not yet a dictionary.

Use the ast.literal_eval() function to load it into an actual dictionary:

>>> ast.literal_eval('''\
... {'gamess': "416.gamess/exe/gamess",
...             'sjeng': '458.sjeng/exe/sjeng',
...             'soplex': '450.soplex/exe/soplex',
...             'astar': '473.astar/exe/astar',
...            }''')
{'astar': '473.astar/exe/astar', 'sjeng': '458.sjeng/exe/sjeng', 'gamess': '416.gamess/exe/gamess', 'soplex': '450.soplex/exe/soplex'}
>>> cmd_list = _
>>> cmd_list['sjeng']
'458.sjeng/exe/sjeng'

If you control the output format, you may want to rethink the strategy though; there are better formats for storing the same information.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343