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]
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.
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.
Using map() with Dictionary Since the dictionary is an iterator, you can make use of it inside map() function.
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.
You can use the dictionary
's get
function
list(map(dictionary.get, list_to_be_mapped))
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]
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