Given the following dictionary:
dct = {'a':3, 'b':3,'c':5,'d':3}
How can I apply these values to a list such as:
lst = ['c', 'd', 'a', 'b', 'd']
in order to get something like:
lstval = [5, 3, 3, 3, 3]
To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.
Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. Use map() to apply fn to each value of the list. Use zip() to pair original values to the values produced by fn .
In Python to convert the keys of a dictionary to a list. First, we have to declare a dictionary and insert it into key-value pairs. Now we will use dict. keys() method to get the list of keys from the dictionary.
Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With