0

I have a list of dict for example,

[{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]

Now, I have to retrieve the following list from this dict without using list comprehension

[u'Library', u'Arts', u'Sports']

Is there any way to achieve this in python? I saw many similar questions, but all answers were using list comprehension.

Any suggestion is appreciated. Thanks in advance.

4

4 回答 4

10

你可以使用itemgetter

from operator import itemgetter

categories = map(itemgetter('name'), things)

但是列表理解也很好。列表推导有什么问题?

于 2013-07-21T14:15:02.330 回答
5

你可以map()在这里使用。map()将 lambda 应用于 的每个项目testList并将其作为列表返回。

>>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]
>>> map(lambda x: x['name'], testList)
[u'Library', u'Arts', u'Sports']
于 2013-07-21T14:13:00.907 回答
4

您可以map()使用lambda

>>> dlist = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]

>>> map(lambda d: d['name'], dlist)
[u'Library', u'Arts', u'Sports']
于 2013-07-21T14:13:47.423 回答
1

这里 -

ltemp = [] 
for i in dictT:
    ltemp.append(i['name'])

ltemp 是必需的列表。dictT 是您的字典列表。

于 2013-07-21T14:13:29.773 回答