Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is nested dictionary in design ok?

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!)?

like image 465
Vishal Avatar asked Dec 06 '22 03:12

Vishal


2 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 :)

like image 110
mthurlin Avatar answered Dec 10 '22 10:12

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.

like image 28
Mike Graham Avatar answered Dec 10 '22 10:12

Mike Graham