Home > Mobile >  Extract first value from each list in a dictionary
Extract first value from each list in a dictionary

Time:03-10

I have this dictionary which is being returned from a function:

{'Revenue':TotalRevExInt, 'Expenses':Expenses, 'IntExpense':NetIntExp, 'Depr&Amort':DeprAndAmort}

Each item is a list of 10 numbers e.g.

Expenses = [1,2,3,4,5,6,7,8,9,10]

I'm stumped at trying to extract the first number from each list in the dictionary, so the output would essentially be [1,1,1,1]. I've had a look around but cant seem to find the right answer. Does anyone know the best way to approach this? Cheers.

CodePudding user response:

To extract the first value of each list, you could use list comprehension to iterate on your dict values and then use indexing on each list to access the first element. Of course, this assumes that the order of the output might not matter:

[list_of_values[0] for list_of_values in my_dict.values()]

Note: Since Python 3.7 you should be able to assume that your dict instance behaves like an OrderedDict, but it's still not widely recommended to assume this property.

CodePudding user response:

You could use .values() and have something like this

ans = []
for i in Expenses.values():
    ans.append(i[0])
  • Related