king
king

Reputation: 1344

Best Way To Lookup Items In Multi-Dimensional List in Python

I know this is "simple", but I can't figure this out or find help on this and it's driving me crazy. I want to make a multi dimensional list that has multiple values, like 3 values for each row for example, and I want to be able to find out any of the row's information based on a given value.

For example, if I have the following data:

Name: Dog, Color: Brown, Behavior: Happy Name: Cat, Color: Black, Behavior: Sad Name: Bird, Color: Green, Behavior: Energetic

So I make a list like this:

theList = []

theList = [{"dog","brown","happy" }, {"cat","black", "sad"}, {"bird","green", "energetic"} ]

How can I find out the information for something based on a value? For example, I want to find out the color of the dog? How would I search the list for "dog" and find out what the value is for the second thing (value [1] within the list section that contains "dog"?

Or is it easier to do a multi-dimensional dictionary for this?

Upvotes: 2

Views: 1951

Answers (2)

AChampion
AChampion

Reputation: 30278

This really depends on what your intention is. As pointed out by @ViníciusAguiar you could use the animal as a key in the dictionary but this only makes sense if name is your primary lookup and you don't have multiple dogs with different colours and behaviours.

Alternatively, if this really is a table that you want to ask multiple questions of then a list of dicts maybe the appropriate structure, e.g.:

In []:
data = [{"name":"dog", "colour":"brown", "behaviour":"happy"},
        {"name":"cat", "colour":"black", "behaviour":"sad"},
        {"name":"bird", "colour":"green", "behaviour":"energetic"} ]

[d['colour'] for d in data if d['name'] == 'dog']

Out[]:
['brown']

Here is the equivalent for loop:

In []:
result = []
for d in data:
    if d['name'] == 'dog':
         result.append(d['colour'])
result

Out[]:
['brown']

But you can also ask other questions like which animals are green:

In []:
[d['name'] for d in data if d['colour'] == 'green']

Out[]:
['bird']

If you can also use third party libraries then there is pandas, which is good at handling table data, e.g.:

In []:
import pandas as pd
df = pd.DataFrame(data)
df

Out[]:
   name colour  behaviour
0   dog  brown      happy
1   cat  black        sad
2  bird  green  energetic

In []:
df[df['name']=='dog']['colour']

Out[]:
0    brown

Upvotes: 6

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

Just use the name of the pet as a key in dictionary:

myDict = {  "dog": {"Color":"brown","Behaviour":"happy"},
            "cat": {"Color":"black","Behaviour":"sad"},
            "bird": {"Color":"green","Behaviour":"energetic"}}

For example, I want to find out the color of the dog?

>>> myDict["dog"]["Color"]
'brown'

Upvotes: 1

Related Questions