Search code examples
pythonlistreplace

How to replace elements in a list using dictionary lookup


Given this list

my_lst = ['LAC', 'HOU', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

I want to change its 0th and 1st values according to the dictionary value:

def translate(my_lst):
    subs = {
        "Houston": "HOU", 
        "L.A. Clippers": "LAC",

    }

so the list becomes:

['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

Solution

  • If all values are unique then you should reverse the dict first to get an efficient solution:

    >>> subs = {
    ...         "Houston": "HOU", 
    ...         "L.A. Clippers": "LAC",
    ... 
    ...     }
    >>> rev_subs = { v:k for k, v in subs.items()} # subs.iteritems() In Python 3
    >>> [rev_subs.get(item, item)  for item in my_lst]
    ['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']
    

    If you're only trying to update selected indexes, then try:

    indexes = [0, 1]
    for ind in indexes:
        val =  my_lst[ind]
        my_lst[ind] = rev_subs.get(val, val)