views:

151

answers:

2

I am writing some and I need to pass a complicated data structure to some function.

The data structure goes like this:

{ '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 ways how to simplify writing such massive data structures?

PS. I made up this structure but my real structure is very similar tho.

+2  A: 
  1. Use objects. You are working with basic types like strings and dictionaries while objects are more powerful.
  2. Use function arguments. You can pass the the first-level keys in your dictionary as arguments to your function:
def yourfunction(animals, fruits)
    # do things with fruits and animals
    pass
Otto Allmendinger
Or he can leave his structure as it is and pass it as `yourfunction(*his_variable)`
voyager
@voyager less expressive in my opinion
Otto Allmendinger
+5  A: 

Other languages would solve this problem with objects or structs-- 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 ahead of time what form the data is going to take. If you don't, then maps/lists are your only choice ;-)

Denise