Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have a list in which each element is a single number in a list. How do I extract the numbers?

I am a python beginner and I have a list. It goes like this:

my_list=[
     {"first":"1"}, 
     {"second": "2"}, 
     {"third": "1"}, 
     {"four": "5"}, 
     {"five":"5"}, 
     {"six":"9"},
     {"seven":"7"}
    ]

I want to extract the single values of this list.
I wrote the following piece of code:

values = []

for element in my_list:
    val = list(element.values())
    values.append(val)

print(values)

This is my output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['1'], ['2'], ['1'], ['5'], ['5'], ['9'], ['7']]

I want only the value numbers to be in my list. [1,2,1,5,5,9,7]
How do I fix my code?

>Solution :

You are almost correct but list(element.values()) gives you a list, You don’t want to append the list itself but the only item inside it. So do a subscription:

values.append(val[0])

or you can use .extend() instead of .append():

values.extend(val)

If I were to write this, I would do one of these:

print([list(d.values())[0] for d in my_list])
print([next(iter(d.values())) for d in my_list])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading