How to simplify the creation of huge data structures in Python

I am writing some, and I need to pass a complex data structure for some function.

The data structure is as follows:

{ 'animals': [ 'cows', 'moose', { 'properties': [ 9, 26 ] } ] 'fruits': { 'land': [ 'strawberries', 'other berries' ], 'space': [ 'apples', 'cherries' ] } } 

This structure looks pretty ugly to me. Can you think of a way to simplify writing such massive data structures?

PS. I made up this structure, but my real structure is very similar to that.

+4
source share
2 answers

Other languages ​​will solve this problem with objects or structures - so something like:

 class whatever: animals = AnimalObject() fruits = FruitObject() class AnimalObject: animals = ['cows','moose'] properties = [9,26] class FruitObject: land = ['strawberries', 'other berries'] space = ['apples', 'cherries'] 

Of course, this only works if you know in advance what form the data will collect. If you do not, maps / lists are your only choice :-)

+5
source
  • Use objects. You work with basic types such as strings and dictionaries, while objects are more powerful.
  • Use function arguments. You can pass the first level keys in the dictionary as arguments to your function:
  def yourfunction (animals, fruits)
     # do things with fruits and animals
     pass
+2
source

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


All Articles