Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping dictionary value to list

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] 
like image 546
ulrich Avatar asked Oct 12 '15 10:10

ulrich


People also ask

How do you turn the values of a dictionary into a list?

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.

How do I map a dictionary to a list?

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 .

Can you convert a key-value dictionary to list of lists?

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.

Can dictionary values be a list Python?

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).


2 Answers

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] 
like image 144
wim Avatar answered Sep 19 '22 03:09

wim


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.

like image 41
Sanjay T. Sharma Avatar answered Sep 21 '22 03:09

Sanjay T. Sharma