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.
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]
lstval = [d[x] for x in lst]
Don't name your dictionary dict
. dict
is the name of the type.
I would use a list comprehension:
listval = [dict.get(key, 0) for key in lst]
The .get(key, 0)
part is used to return a default value (in this case 0) if no element with this key exists in dict
.