Tuesday, May 29, 2012

File paths and nested dictionaries

Really, I just want to boost the pagerank of this page: http://code.activestate.com/recipes/475156-using-reduce-to-access-deeply-nested-dictionaries/

I had an issue where I had a list, say [1,3,4,6,7, "result"], which I wanted to smoosh into a nested dictionary and get back easily. I found my own way to store said items (built up programmatically in the course of other logic), but I wanted an easy way to get them.

I will now reproduce the solution from the above page in full, for your convenience:

# In your hand you have a dict instance representing the database 'object'
dbo={'m':{'d':{'v':{'version':1}}}}

# You know this thing corresponds to a table whose rows follow some convention
# indicating 'depth', say '__' hapens to be the seperator.

# You wan't to access a particular element, but you know it only by its column
# name 'm__d__v__version'

name='m__d__v__version'

version = reduce(dict.get, name.split('__'), dbo)

assert version == 1

foo = reduce(dict.get, 'm__d__v__foo'.split('__'), dbo)

assert foo == None