4

Assuming I have the following data structure

theValues = [
  { "id": "123", "name": "foo" },
  { "id": "321", "name": "bar" },
  { "id": "231", "name": "baz" }
]

What's the best Pythonistic way to get a list of the IDs [123,321,231] ?

If this were javascript, I'd probably just use filter on each element in the list with an anonymous function, but I can't seem to find a Python equivalent. I know I could do the following:

myList = []
for v in theValues: myList.append(v["id"])

Ultimately, I'd like to reduce the list of dictionaries to a comma-separated list, which I suppose I could do with a join... though that syntax still looks weird to me. Is there a better way?

myListIds = ",".join( myList )

Is that the most common way of doing it? In PHP, I could do something like:

$myListIds = implode(",", array_map( values, function( v ) { return v["ID"]; } ));
Sreeragh A R
  • 2,871
  • 3
  • 27
  • 54
Armstrongest
  • 15,181
  • 13
  • 67
  • 106

2 Answers2

10
values = [
  { "id": "123", "name": "foo" },
  { "id": "321", "name": "bar" },
  { "id": "231", "name": "baz" }
]
ids = [val['id'] for val in values]
print(ids)

Based on this answer

Sreeragh A R
  • 2,871
  • 3
  • 27
  • 54
4

There is a way to map with Python as well, see below the example.

values = [
  { "id": "123", "name": "foo" },
  { "id": "321", "name": "bar" },
  { "id": "231", "name": "baz" }
]

my_list = map(lambda x: x["id"], values)

print(my_list)

Output:

['123', '321', '231']

About the comma separated list, if you would like to have a string, you can use join as below to obtain it:

print(", ".join(my_list))

If you would like to make it in one line of code, here is how you should do it:

print(", ".join(map(lambda x: x["id"], values)))

Output:

123, 321, 231
Jonathan Gagne
  • 4,241
  • 5
  • 18
  • 30