[英]How do I list occurrences of certian values found in a dictionary in a list in python?
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
. 如何获取在
created_by
找到的值的列表。 (eg ['adam','admin']
) (例如
['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. 如果您绝对确定
dave
包含的每个字典中的键都是'created_by'
则可以忽略if 'created_by' in x
部分中的KeyError
如果在这种情况下缺少该键,则会引发KeyError
。
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
:
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
factory仅返回唯一值,然后可以使用set
list
factory来获取list
:-
>>> 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'. 列表理解的一个进步是对可能没有'created_by'的项目使用if条件。 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.