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
. (eg ['adam','admin']
)
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
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']
将其放在集合中,然后返回列表...
list(set(d['created_by'] for d in dave))
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.