python – Mapping dictionary value to list

python – Mapping dictionary value to list

Using a list comprehension:

>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]

Using map:

>>> [*map(dct.get, lst)]
[5, 3, 3, 3, 3]

You can use a list comprehension for this:

lstval = [ dct.get(k, your_fav_default) for k in lst ]

I personally propose using list comprehensions over built-in map because it looks familiar to all Python programmers, is easier to parse and extend in case a custom default value is required.

python – Mapping dictionary value to list

You can iterate keys from your list using map function:

lstval = list(map(dct.get, lst))

Or if you prefer list comprehension:

lstval = [dct[key] for key in lst]

Leave a Reply

Your email address will not be published.