Addressing Nested Dictionaries in Python

March 13, 2012

I think that post title is right. Essentially I mean dynamically accessing attributes from nested dictionaries or tuples.

Let’s say you’ve got a JSON response like this:

The JSON module would convert that into nested dictionaries, like this:

In my case, I was trying to provide a runtime specified format string which could use any of the values at any depth.

There isn’t (to my knowledge) an easy way to address into a deep structure with a single string. I considered value based format strings ('%(name)s' but there is no way to descend from there either.

My solution was to use a dot notation and evaluate it for field values.

This requires a strict policy not to use dots in your keys, but that is not an issue for my use case.

Here is my code for the dot notation:

And here it is in use against the object above:

The next (optional) step would be to create a wrapper object.

Which we can then use like so:

While this is just sugar, it does look nice doesn’t it? To be complete you would want to implement the other sequence methods such as __setitem__

So that’s my fix – what’s yours?

Categories: Geek
Tags: , ,

Leave A Comment

Your email will not be published.