Is a nested dictionary constructive?

My data is structured in such a way that I finished creating a nested dictionary in my design, for example:

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

This is a common thing! or do we have other better alternatives (using objects!)?

+4
source share
5 answers

Nested dicts do nothing wrong. Everything can be a dict value, and it can make sense for the dict to be one.

At a time when people make nested voice recorders, their problems can be solved a little easier by using a dict with tuples for keys. Instead of accessing the value as d[a][b][c] , then the value will be available as d[a, b, c] . It is often easier to set up and work.

+7
source

You can 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 Zen of Python says that an apartment is better than nested :)

+7
source

At first, they may seem like a good idea, but usually you will need more information / functionality from them. If this happens, your first reaction might be β€œI need more hashes,” but all of this can be avoided by using a simpler hierarchy ... it would be easier.

+1
source

I would not create complex data structures similar to what is in the code itself. There is too much risk of making a mistake with punctuation, and anyone reading the code will be confused by this. It is much better to place your persistent data in a simple way without embedding data structures. Then, if you need to have a nested dictionary in the application, create it with the 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'}} 
0
source

Maybe one nested dictionary is fine ... but even then you ask it to get confused later, and there is a pretty good chance that if you are already doing nested things, you will need additional information in it later.

In general, I would say take a step back and see if all this information is needed in the dictionaries. First try to simplify it. If it is really necessary, I would try to make a simple class for it. Maybe a little too much, but, as I said, if you are already going along this road, you will probably end up adding more information later. It's easier to modify a class than trying to figure out all this nested information and make your code later.

0
source

Source: https://habr.com/ru/post/1301862/


All Articles