0

Given a list of dictionaries, each dictionary with only one pair key-value, and each one with different keys and value,
how to get a list of all values of the dictionaries?

example:

Given

my_list = [
            {'A': 'first'}, 
            {'B': 'second'}, 
            {'C': 'third'}, 
            {'D': 'fourth'}, 
            {'E': 'fifth'}, 
            {'F': 'sixth'}
          ]

and I want to get

My_list_2 = [
             'first', 
             'second', 
             'third', 
             'fourth', 
             'fifth', 
             'sixth'
            ]

how can I do it?

I have tryed with

my_list_2 = [ el.values() for el in my_list ] 

but I get

[dict_values(['first']),
 dict_values(['second']),
 dict_values(['third']),
 dict_values(['fourth']),
 dict_values(['fifth']),
 dict_values(['sixth'])]
Tms91
  • 3,456
  • 6
  • 40
  • 74
  • Sorry, I dismissed your suggestion without evaluating carefully. The answer you mention gives actually a solution to my problem, since the expression it suggests, i.e. `next(iter(d.values()))`, can be used to build this list comprehension: `[ next(iter(d.values())) for d in my_list]`, that is the result I seek. I might be more efficient than the solution purposed by @Suyog Shimpi, but I thing this latter answer is more clear and easier to understand. – Tms91 Sep 09 '21 at 13:15

2 Answers2

4

You can use like this

my_list_2 = [ ol for el in my_list for ol in el.values() ]

Result would be -

['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
Suyog Shimpi
  • 706
  • 1
  • 8
  • 16
1

try this:

My_list_2 = [v for m in my_list for k,v in m.items()]
# ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30