Sam
Sam

Reputation: 161

How to get a specific value from list of lists in Python?

I have a CSV file and I am loading all the rows into a list of lists

here is the code for loading the rows into the list:

import csv
with open('ratios.csv', newline='') as csvfile:
    data = list(csv.reader(csvfile))
print(data)

output of the code is something like this :

[['Short', 'Total', 'points'], ['asd', '5888', '0.4829'], ['vsd', '5010', '0.6408'], ['trd', '4394', '0.3863'], ['axc', '2366', '0.3629'], ['gtr', '1390', '0.7145'], ['ntr', '1310', '0.7527'], ['try', '1290', '0.2821']]

Now I am trying to get only a certain value from the list, for example : value of interest is always the 3rd element of the list depending on the first element

Let's say I only need the third element of the list which has the first element 'trd'. So from above example the list of interest will be ['trd', '4394', '0.3863'] and the value I need is '0.3863'.

How do I go about it ?

Upvotes: 0

Views: 2528

Answers (3)

norie
norie

Reputation: 9857

You could use filter with lambda to find all the lists where the first element is trd.

You could then loop through the result to get the 3rd element from each list the filter returned.

data = [
    ["Short", "Total", "points"],
    ["asd", "5888", "0.4829"],
    ["vsd", "5010", "0.6408"],
    ["trd", "4394", "0.3863"],
    ["axc", "2366", "0.3629"],
    ["gtr", "1390", "0.7145"],
    ["ntr", "1310", "0.7527"],
    ["try", "1290", "0.2821"],
]


filtered_data = filter(lambda row: row[0] == "trd", data)

for trd in filtered_data:
    print(trd[2])

Upvotes: 1

Samwise
Samwise

Reputation: 71424

If you want to be able to access rows according to their Short value, why not make a data dict that is structured that way, rather than a flat list that you'll have to iterate over every time you want something from it?

>>> import csv
>>> with open('ratios.csv') as csvfile:
...     data = {row['Short']: row for row in csv.DictReader(csvfile)}
...
>>> data['trd']['points']
'0.3863'

Always set up your data the way that will make your life easier, rather than dumping it into the first format you think of and then figuring out after the fact how to get it back out. :)

Upvotes: 2

Thomas
Thomas

Reputation: 10055

You could just use a list comprehension along with an if statement to find the third element of the sublist/triplet...

with open('ratios.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    values = [row[2] for row in reader if row[0] == 'trd']
    print(values)

Which is equivalent to:

import csv

with open('ratios.csv', newline='') as csvfile:
    values = []
    for row in csv.reader(csvfile):
        if row[0] == 'trd':
            values.append(row[2])
    print(values)

Upvotes: 1

Related Questions