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