Reputation: 990
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.
Upvotes: 0
Views: 123
Reputation: 298046
You could use itemgetter
:
from operator import itemgetter
categories = map(itemgetter('name'), things)
But a list comprehension is good too. What's wrong with list comprehensions?
Upvotes: 10
Reputation: 213193
You can use map()
with 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']
Upvotes: 4
Reputation: 1889
Here -
ltemp = []
for i in dictT:
ltemp.append(i['name'])
ltemp is required list. And dictT is your list of dictionaries.
Upvotes: 1
Reputation: 34483
You could use map()
here. map()
applies the lambda to every item of testList
and returns it as a list.
>>> 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']
Upvotes: 5