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

Question:

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:

[['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?

Asked By: Prerk

||

Answers:

The .values() return a dict_values object, which is an iterable and since you’re converting it to a list, so you can extract the first index in order to get your desired format like this

values = []

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

print(values)
Answered By: Divyessh

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])
Answered By: S.B

You can do like this,

In [1]: list(map(lambda x:list(x.values())[0], my_list))
Out[1]: ['1', '2', '1', '5', '5', '9', '7']
Answered By: Rahul K P

When in doubt, simply pop the (most recently added) item:

>>> my_list = [
...     {"first": "1"},
...     {"second": "2"},
...     {"third": "1"},
...     {"four": "5"},
...     {"five": "5"},
...     {"six": "9"},
...     {"seven": "7"}
... ]
>>> [int(d.popitem()[1]) for d in my_list]
[1, 2, 1, 5, 5, 9, 7]
Answered By: rv.kvetch
my_list=[
     {"first":"1"},
     {"second": "2"},
     {"third": "1"},
     {"four": "5"},
     {"five":"5"},
     {"six":"9"},
     {"seven":"7"}
     ]
values = [int(element.popitem()[1]) for element 
in my_list]
print(values)
Answered By: Mylar Jadadeli
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.