0

My question is difficult to word, what I mean is:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = ['b', 'a', 'b', 'c', 'c']
my_list_output = some_func(my_list, my_dict)
print(my_list_output)
# [2, 1, 2, 3, 3]

Is there a neat, somewhat readable way to do this? Thanks

Fin H
  • 71
  • 2
  • 13

3 Answers3

1

Chack this

def some_func(my_dict,my_list):
   newList=[my_dict[k] for k in my_list if k in my_dict]
   return newList


my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = ['b', 'a', 'b', 'c', 'c']
my_list_output= some_func( my_dict,my_list)

print (my_list_output)
BiswajitPaloi
  • 586
  • 4
  • 16
1

This can be a single-line function if you write it as a list comprehension:

>>> my_dict = {'a': 1, 'b': 2, 'c': 3}
>>> my_list = ['b', 'a', 'b', 'c', 'c']
>>> def some_func(some_list, some_dict):
...     return [some_dict[x] for x in some_list]
...
>>> some_func(my_list, my_dict)
[2, 1, 2, 3, 3]
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

try this

MY_DICT = {'a': 1, 'b': 2, 'c': 3}
KEYS_TO_LOOK = ['b', 'a', 'b', 'c', 'c']

def my_list_function(dictionary, keys):
    """
        function that makes a list from a dictionary ,out of a list of keys

    Parameters
    ----------
    :param dictionary: dataframe de datos a procesar
    :type:   dict
    :example    {'a': 1, 'b': 2, 'c': 3}

    :param keys: list of keys to look for
    :type:  list
    :example    ['b', 'a', 'b', 'c', 'c']   
    
    :returns:  list
    """
    
    list_to_print = []
    
    for key in keys:
        list_to_print.extend([dictionary[key]])
    return list_to_print

my_list_output = my_list_function(dictionary = MY_DICT, keys = KEYS_TO_LOOK)

print(my_list_output)