user4611642
user4611642

Reputation: 27

How do I make hierarchical lists python

I'm trying to create hierarchy lists python in python. For example, There are several states. In each state there are several counties, in each county they are several cities. Then I would like be able to call those. I've tried creating list and appending lists to those list but I can't get to that to work. It also gets really messy. Thanks

I just found this example:

tree = [
    ['Food', [
         ['Fruit', [
               ['Red', ['Cherry', 'Strawberry']],
               ['Yellow', ['Banana']],
         ]],
         ['Meat', [
               ['Beef', 'Pork']
         ]],
    ]],
]

Now my question would just be, is this the best way? how to call specific things? If I use...

print tree[0]

it will give me everything. When I try

print tree[0[1]]

I get a type TypeError: 'int" object has no attribute '__getitem_' Thanks

Upvotes: 0

Views: 4096

Answers (2)

Luke
Luke

Reputation: 5708

The direct answer to your question is that the list was likely created correctly, but you are not accessing it correctly.

You access the nested lists like this:

tree[0][1]...

not like this

tree[0[1[..]]]

However, you should use a dictionary, not a list. It will make your look ups much more simple and they will be more efficient as well.

If you are interested in finding out how the dictionaries work. Google the term 'Associative array'. They are also known as hashes or hash tables.

Also, rather than using the term hierarchical the term multi-dimensional is more common.

e.g. this:

mylist=[
        [...],
        [...],
        .
        . 
       ]

Is a 2D list

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54223

Dictionaries are the way to go.

d = {'food': 
        {'fruit':
            {'color':
                {'red': ['Cherry', 'Strawberry']},
                {'yellow': ['Banana']},
            },
        },
        {'meat': ['Beef', 'Pork']}
    }

Now you can do:

for item in d['food']['fruit']['color']['red']:
    print(item)
# Cherry
# Strawberry

Upvotes: 2

Related Questions