Search code examples
pythonarrayspython-3.xdictionaryarray-map

Pythonic way of getting a list of IDs from a dictionary


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"]; } ));

Solution

  • 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