Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map list from dictionaries

I am new to python and have looked at numerous pages for this.

I know pandas data frames have this mapping functionlity:

dictionary = {a:1, b:2, c:6}

df['col_name'] = df.col_name.map(dictionary) #df is a pandas dictionary

How do I do something similar for lists, i.e.,

mapped_list = list_to_be_mapped.map(dictionary)

where in

list_to_be_mapped = [a,a,b,c,c,a]
mapped_list       = [1,1,2,6,6,1]
like image 237
agent18 Avatar asked Mar 31 '16 09:03

agent18


People also ask

Can you map a dictionary Python?

We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program.

How do you turn a dictionary into a list?

Dictionary to List Using . items() method of the dictionary is used to iterate through all the key-value pairs of the dictionary. By default, they are stored as a tuple (key, value) in the iterator. Using list() will get you all the items converted to a list.

Can map be used with dictionary?

Using map() with Dictionary Since the dictionary is an iterator, you can make use of it inside map() function.

How do I map a value to a list in Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.


2 Answers

You can use the dictionary's get function

list(map(dictionary.get, list_to_be_mapped))
like image 74
Sevanteri Avatar answered Oct 16 '22 08:10

Sevanteri


If you only want to map those values actually in your dictionary I would suggest the following:

dictionary = {'a': 1, 'b': 2}
list_to_be_mapped = ['a', 'a', 'b', 'c', 'c', 'a']
[dictionary.get(a) if dictionary.get(a) else a for a in list_to_be_mapped]

which returns

[1, 1, 2, 'c', 'c', 1]
like image 28
grofte Avatar answered Oct 16 '22 07:10

grofte