0

I have a dictionary which contains a certain number of key/value pairs such as:

d = { "v1": 1, "v2": 2, "v3":3, "v4": 4 }

and a list containing the keys in a certain order:

l = [ "v2", "v3", "v1", "v4" ]

how can I obtain a list of values using the order of l in an elegant way ?

[ 2, 3, 1, 4]

The only thing I could think of is:

[ d[k] for k in l ]

Same question if I wanted to obtain a tuple.

BlueTrin
  • 9,610
  • 12
  • 49
  • 78

1 Answers1

3

For Python 2.x , try using -

>>> d = { "v1": 1, "v2": 2, "v3":3, "v4": 4 }
>>> l = [ "v2", "v3", "v1", "v4" ]
>>> map(d.get,l)
[2, 3, 1, 4]

If you are using Python 3.x , map function returns a map object which you can iterate over, for converting to list use list function , Example -

>>> list(map(d.get,l))
[2, 3, 1, 4]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176