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.

4
  • 2
    possible duplicate of Get a list of values from a list of dictionaries in python Commented May 31, 2015 at 4:38
  • I'm not working with a dictionary, but I'll see if I can adapt that Q's answer. Commented May 31, 2015 at 4:41
  • 1
    One line.. a good use-case for list comprehension Commented May 31, 2015 at 4:43
  • I see. Both map and list comprehensions are new to me. Great to be introduced! Commented May 31, 2015 at 4:45

3 Answers 3

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] 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

If you're an experienced programmer checking out Python, you'll probably enjoy the book Dive into Python (www.diveintopython.net).
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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.