Tech and travel

Using map with a dictionary in Python

2009-07-21

When you have a dictionary in Python like this :

mydict={'first':1, 'second':2, 'third':3}

and you want to get the values into a list with a certain order you can do this :

mylist=[mydict['first'], mydict['second'], mydict['third']]

However, that can get a bit verbose if there are a lot of entries. For every entry you have to repeat ‘mydict’. An elegant way of solving this is using the map function :

mylist=map(mydict.get,['first', 'second', 'third'])

This applies to ‘get’ function of mydict to each of the arguments given in the list. This ‘get’ function is the equivalent of calling mydict[‘some index’] .

List comprehensions can be used a lot of times instead of map. That’s the case here as well :

mylist=[mydict[x] for x in ['first','second','third']]

This is arguably easier to understand than the version using map.

Copyright (c) 2024 Michel Hollands