0

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

4
  • Please provide concrete examples of what you need to accomplish. What does "calling" lists mean, etc. Commented Feb 26, 2015 at 20:28
  • 3
    I think you want a dictionary of dictionaries and/or lists. {'country_1': {'state_1': {'county_1': ['city_1', 'city_2',], 'county_2': ['city_3', 'city_4']}, 'state_2': {'county_3': ... etc. Commented Feb 26, 2015 at 20:29
  • 1
    Do not use lists for this but use a dictionary. It is the only way to bind a parent 'country' or 'state' to a child. Commented Feb 26, 2015 at 20:50
  • Instead of print tree[0[1]], try print tree[0][1]. Commented Feb 26, 2015 at 21:08

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.