Search code examples
pythonlistsublist

Retrieving values of sublists within a list


so I have a list which I retrieved from converting a data frame to a list that looks like the following (it goes on for many countries):

list = [[NL, Q1, 1400], [NL, Q2, 1800], [NL, Q3, 1900], [NL, Q4, 2000], [FRA, Q1, 2400],[FRA, Q1, 2600], ...]

Now, I need to to retrieve the third values for each country and append them to their own list, so the output should be:

NL = [1400, 1800, 2000]
FRA = [2400, 2600, ...]

How can I achieve this? I tried to use a for loop statement, but then I only get the sublists.


Solution

  • I would construct a dictionary, where for each key it contains a list of values of that key in the original list.

    from collections import defaultdict
    
    values_per_country = defaultdict(list)
    for country, _, value in li:
        values_per_country[country].append(value)
    

    Then you can get all the values for, say, NL, as values_per_country["NL"] and optionally assign it to a variable if you wish.