[英]convert list of dicts to list
I have a list of fields in this form 我有一个这种形式的字段列表
fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
I'd like to extract just the names and put it in a list. 我想提取名称并将其放入列表中。 Currently, I'm doing this:
目前,我这样做:
names = []
for field in fields:
names.append(field['name'])
Is there another way to do the same thing, that doesn't involve looping through the list. 还有另一种方法可以做同样的事情,不涉及循环列表。
I'm using python 2.7. 我正在使用python 2.7。
Thanks for your help.! 谢谢你的帮助。!
You can use a list comprehension: 您可以使用列表理解:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
Take a look at list comprehensions 看看列表理解
Maybe try: 也许试试:
names = [x['name'] for x in fields]
Example: 例:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [x['name'] for x in fields]
['count', 'type']
If names
already exists you can map (creating it in the same manner) to append each member of the new list you've created: 如果
names
已经存在,您可以映射 (以相同的方式创建names
)以附加您创建的新列表的每个成员:
map(names.append, [x['name'] for x in fields])
Example: 例:
>>> a = [1, 2 ,3]
>>> map(a.append, [2 ,3, 4])
[None, None, None]
>>> a
[1, 2, 3, 2, 3, 4]
Edit: 编辑:
Not sure why I didn't mention list.extend
, but here is an example: 不知道为什么我没有提到
list.extend
,但这是一个例子:
names.extend([x['name'] for x in fields])
or simply use the +
operator: 或者只是使用
+
运算符:
names += [x['name'] for x in fields]
you can also filter "on the fly" using an if
statement just like you'd expect: 您也可以使用
if
语句过滤“动态”,就像您期望的那样:
names = [x['name'] for x in fields if x and x['name'][0] == 'a']
Example: 例:
>>> l1 = ({'a':None}, None, {'a': 'aasd'})
>>> [x['a'] for x in l1 if (x and x['a'] and x['a'][0] == 'a')]
['aasd']
that will generate a list of all xs with names that start with 'a' 这将生成一个名称以'a'开头的所有x的列表
names = [x['name'] for x in fields]
would do. names = [x['name'] for x in fields]
会这样做。
and if the list names
already exists then: 如果列表
names
已存在,则:
names += [x['name'] for x in fields]
If the form is well defined, meaning, 'name' must be defined in each dict, then you may use: 如果表格定义明确,意思是,必须在每个字典中定义“名称”,那么您可以使用:
map(lambda x: x['name'], fields)
else, you may use filter
before extracting, just to make sure you don't get KeyError
否则,你可以在解压缩之前使用
filter
,只是为了确保你没有得到KeyError
map(lambda x: x['name'], filter(lambda x: x.has_key('name'), fields))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.