Home > Back-end >  I have a list in which each element is a single number in a list. How do I extract the numbers?
I have a list in which each element is a single number in a list. How do I extract the numbers?

Time:10-03

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?

CodePudding user response:

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])

CodePudding user response:

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)

CodePudding user response:

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']

CodePudding user response:

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]
  • Related