Igor K.
Igor K.

Reputation: 877

Get list from dictionary with list

My data is organized like this:

d={1: [44, 56.5238], 2: [63, 56.8663], 3: [93, 55.7313], 4: [112, 55.5425]}

I want to create list with first values in these small lists:

new_list=[44, 63, 93, 112]

My ugly way to do it:

new_list=[]
for item in d.values():
    new_list.append(item[0])

Can I do it in better and shorter way, may be in one line?

Upvotes: 2

Views: 59

Answers (1)

Luke
Luke

Reputation: 49

new_list = [d[key][0] for key in d]

That's a list comprehension -- it loops throught the keys in d, and then gets the first item of each value, using that key.

Upvotes: 1

Related Questions