3

How can I quickly convert a list of dictionaries to a simple list of just the values if the order is not important?

For example:

results = [{'id':'abcd'},
           {'id':'bcde'},
           {'id':'cdef'}]

to simply

results = ('abcd','bcde','cdef')
martineau
  • 119,623
  • 25
  • 170
  • 301
ensnare
  • 40,069
  • 64
  • 158
  • 224

4 Answers4

3

You can try this:

>>> results = [{'id':'abcd'},
...            {'id':'bcde'},
...            {'id':'cdef'}]
>>>
>>> tuple(d['id'] for d in results)
('abcd', 'bcde', 'cdef')

Note that this is not a list but rather a tuple. If you want a list instead:

>>> [d['id'] for d in results]
['abcd', 'bcde', 'cdef']
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

This should do it:

>>> [val for dic in results for val in dic.values()]

['abcd', 'bcde', 'cdef']

If you want a tuple, just enclose in tuple with parens instead:

>>> tuple(val for dic in results for val in dic.values())

('abcd', 'bcde', 'cdef')

Both of the above work even if dictionaries have more than one value, and regardless of what the keys in the dictionaries are.

Eli
  • 36,793
  • 40
  • 144
  • 207
  • Is the list created by `dic.values()` needed? – usual me Jul 08 '14 at 12:46
  • Idea is to make things work regardless of keys. It's all in a list comprehension, so Python interpreter can figure out the fastest way of doing it. – Eli Jul 08 '14 at 12:48
1

This will fit your sample data:

import operator
map(operator.itemgetter('id'), results)

e.g.

results = [{'id':'abcd'},
       {'id':'bcde'},
       {'id':'cdef'}]

import operator
print map(operator.itemgetter('id'), results)

>>> ['abcd', 'bcde', 'cdef']

BUT, in a general way, you can chain the values of each dictionary in list:

import itertools
print list(itertools.chain(*map(dict.values, results)))

>>> ['abcd', 'bcde', 'cdef']
Don
  • 16,928
  • 12
  • 63
  • 101
0

It sounds like what you essentially want to do is concatenate the values of all the dictionaries into one list. The built-inreduce()function makes translating that into code relatively easy:

reduce(lambda a, b: a+b, (d.values() for d in results))

will give:

['abcd', 'bcde', 'cdef']

You can add an outer call totuple(), if that's what you really want to get:

('abcd', 'bcde', 'cdef')
martineau
  • 119,623
  • 25
  • 170
  • 301