0

Is there a way to save a python dict structure in config then access it?

For example:

dict = {'root': {'category': {'item': 'test'}}}

# in my config
key = 'some string here'

print (dict[key])

# output
>> test

Solution thanks to answers below:

from functools import reduce
import json

dict = {'root': {'category': {'item': 'test'}}}

# you can put this in your config.ini file
map = '["root", "category", "item"]'

print (reduce(lambda d, k: d[k], json.loads(map), dict))

#output
test
Andrei Stalbe
  • 1,511
  • 6
  • 26
  • 44
  • Related: [Acces python nested dictionary items via a list of keys](http://stackoverflow.com/q/14692690) – Martijn Pieters Aug 17 '13 at 17:00
  • 2
    It is very unclear to me what is being asked. Is "key" something like "root.category.item"? – Markus Unterwaditzer Aug 17 '13 at 17:09
  • Why in the world would you expect the key `'some string here'` to access (or map to) the value stored in `dict['root']['category']['item']`? – martineau Aug 17 '13 at 17:17
  • because I'm iterating a set of dicts that have different structure and keys for the same value being extracted. So instead of using a custom function for each dict structure, I would like to use a global config to predefine each dict structure and keymap. – Andrei Stalbe Aug 17 '13 at 17:26
  • @Andrei Stalbe: No need to encode the list as JSON and then parse it back, just use it as it is. – ivan_pozdeev May 12 '14 at 15:58

2 Answers2

1

Try to use reduce() function or the pickle protocol

Michael
  • 15,386
  • 36
  • 94
  • 143
0

Just use the pickle protocol. You can store virtually anything using that. documentation on pickling: http://docs.python.org/2/library/pickle.html

Hrishi
  • 7,110
  • 5
  • 27
  • 26