0
dave = [{'date':'12/10/12','time':'09:12','created_by':'adam','text':'this'},
        {'date':'28/09/11','time':'15:58','created_by':'admin','text':'that'},
        {'date':'03/01/10','time':'12:34','created_by':'admin','text':'this and that'}]

How to I get a list of the values found in created_by. (e.g. ['adam','admin'])

Robert Johnstone
  • 5,431
  • 12
  • 58
  • 88

4 Answers4

5

A list comprehension will work nicely:

[ x['created_by'] for x in dave if 'created_by' in x ]

If you're absolutely sure that 'created_by' is a key in each dict contained in dave, you can leave off the if 'created_by' in x part -- it would raise a KeyError if that key is missing in that case.

Of course, if you want unique values, then you need to decide if order is important. If order isn't important, a set is the way to go:

set(x['created_by'] for x in dave if 'created_by' in x)

If order is important, refer to this classic question

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

You can use set factory to return only unique value, and then you can get back the list using list factory over your set: -

>>> set(x['created_by'] for x in dave)
set(['admin', 'adam'])

>>> list(set(x['created_by'] for x in dave))
['admin', 'adam']
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Put it in a set, then back to a list...

list(set(d['created_by'] for d in dave))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

An advancement of the list comprehension is to use the if conditional for items that may not have a 'created_by'. When working with messy data this is often required.

list(set(x['created_by'] for x in dave if 'created_by' in x))
>>> ['admin', 'adam']
Matt Alcock
  • 12,399
  • 14
  • 45
  • 61