Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of getting a list of IDs from a dictionary [duplicate]

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"]; } ));
like image 816
Armstrongest Avatar asked Dec 13 '22 13:12

Armstrongest


1 Answers

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

like image 92
Sreeragh A R Avatar answered Dec 22 '22 15:12

Sreeragh A R