1

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.

LazerSharks
  • 3,089
  • 4
  • 42
  • 67

3 Answers3

3

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]
Community
  • 1
  • 1
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
1

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

Paulo Mendes
  • 697
  • 5
  • 16
  • If you're an experienced programmer checking out Python, you'll probably enjoy the book Dive into Python (www.diveintopython.net). – Paulo Mendes May 31 '15 at 06:12
1

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)
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61