2

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?

3
  • 3
    With a list comprehension. However, what version of Python do you use? If it's less than 3.6 then you will have added complications in both approaches (if the output order is important) Commented Aug 8, 2019 at 17:02
  • new_list = [item[0] for item in d.values()]? Commented Aug 8, 2019 at 17:02
  • @pault, it works.Thank you! Commented Aug 8, 2019 at 17:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you can add conditionals in a comprehension as well -- for instance: new_list = [d[key][0] for key in d if type(key) == int and key % 2 == 0] that'll only grab the even numbered key if it's an integer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.