Is nested dictionary in design ok?

Question:

My data is structured in a way that I ended up creating a nested dictionary in my design like:

my_dict = {"a": {"b": {"c":"I am c"}}}   
my_dict["a"]["b"]["c"]

Is it usual! or we have some other better alternatives (using objects!)?

Asked By: Vishal

||

Answers:

You could use a tuple to store your values in a flat dictionary:

d = {}
d[a, b, c] = e

It all depends on what you are doing, but remember that The Zen of Python says that flat is better than nested 🙂

Answered By: mthurlin

There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sense for a dict to be one.

A lot of the time when people make nested dicts, their problems could be solved slightly more easily by using a dict with tuples for keys. Instead of accessing a value as d[a][b][c], then, the value would be accessed as d[a, b, c]. This is often easier to set up and work with.

Answered By: Mike Graham

At first they may seem like a good idea, but usually you’ll find yourself needing more information/functionality from them. If that happens, your first reaction may be “I need more hashes”, but all this can be avoided by using a simpler hierarchy … it would be easier too.

Answered By: Geo

I would not build complex data structures like that in the code itself. There is too great a risk of making a mistake with punctuation, and anyone reading the code will tend to get confused by this. Far better to put your constant data in some simple form, with no nesting of data structures. Then if you need to have a nested dictionary in the app, build it with code.

a = {"a":"I am a"}
b = {"b":"I am b"}
c = {"c":"I am c"}
mydict = {}
mydict["a"] = a
mydict["b"] = b
mydict["c"] = c
print mydict

{'a': {'a': 'I am a'}, 'c': {'c': 'I am c'}, 'b': {'b': 'I am b'}}
Answered By: Michael Dillon

Maybe one nested dictionary is okay… but even then you’re asking to get confused later and there’s a pretty good chance that if you’re already doing nested stuff you’re gonna want more information in it later.

In general I’d say take a step back and see if all that information in the dictionaries is needed. Try to simplify it first. If it really is all needed, I’d try to make a simple class for it. Might be a little overkill but like I said, if you’re going down that road already, you’re probably gonna end up adding more information later. It’s easier to modify a class than it is to try and figure out all that nested information and make your code work with it later.

Answered By: The Jug

You can also use a struct type. Like Dictionary<string, Custom> dict. The struct type is like a dict I guess, but its more rigid.

Answered By: Damian Mark