sreekanth
sreekanth

Reputation: 990

Getting a list of values from a list of dict in python: Without using list comprehension

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

Answers (4)

Blender
Blender

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

Rohit Jain
Rohit Jain

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

svineet
svineet

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

Sukrit Kalra
Sukrit Kalra

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

Related Questions