LazerSharks
LazerSharks

Reputation: 3155

generate list from values of certain field in list of objects

How would I generate a list of values of a certain field of objects in a list?

Given the list of objects:

[ {name: "Joe", group: 1}, {name: "Kirk", group: 2}, {name: "Bob", group: 1}]

I want to generate list of the name field values:

["Joe", "Kirk", "Bob"]

The built-in filter() function seems to come close, but it will return the entire objects themselves.

I'd like a clean, one line solution such as:

filterLikeFunc(function(obj){return obj.name}, mylist)

Sorry, I know that's c syntax.

Upvotes: 1

Views: 2706

Answers (3)

Paul Rooney
Paul Rooney

Reputation: 21619

Just iterate over your list of dicts and pick out the name value and put them in a list.

x = [ {'name': "Joe", 'group': 1}, {'name': "Kirk", 'group': 2}, {'name': "Bob", 'group': 1}]

y = [y['name'] for y in x]

print(y)

Upvotes: 1

Tanveer Alam
Tanveer Alam

Reputation: 5275

Just replace filter built-in function with map built-in function.

And use get function which will not give you key error in the absence of that particular key to get value for name key.

data = [{'name': "Joe", 'group': 1}, {'name': "Kirk", 'group': 2}, {'name': "Bob", 'group': 1}]

print map(lambda x: x.get('name'), data)

In Python 3.x

print(list(map(lambda x: x.get('name'), data)))

Results:

['Joe', 'Kirk', 'Bob']

Using List Comprehension:

print [each.get('name') for each in data]

Upvotes: 3

Paulo Mendes
Paulo Mendes

Reputation: 728

Using a list comprehension approach you get:

objects = [{'group': 1, 'name': 'Joe'}, {'group': 2, 'name': 'Kirk'}, {'group': 1, 'name': 'Bob'}]
names = [i["name"] for i in objects]

For a good intro to list comprehensions, see https://docs.python.org/2/tutorial/datastructures.html

Upvotes: 1

Related Questions