Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace elements in a list using dictionary lookup

Tags:

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'] 
like image 396
nutship Avatar asked Jun 25 '13 11:06

nutship


People also ask

How do you replace elements in a list?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do you update a list of values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')

How do you use replace in a list?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .


2 Answers

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.iteritems()} >>> [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 updated selected indexes, then try:

indexes = [0, 1] for ind in indexes:     val =  my_lst[ind]     my_lst[ind] = rev_subs.get(val, val) 
like image 189
Ashwini Chaudhary Avatar answered Sep 28 '22 15:09

Ashwini Chaudhary


If the values are unique, then you can flip the dictionary:

subs = {v:k for k, v in subs.iteritems()} 

Then you can use .get() to get the value from a dictionary, along with a second parameter incase the key is not in the dictionary:

print map(subs.get, my_lst, my_lst) 

Prints:

['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM'] 
like image 45
TerryA Avatar answered Sep 28 '22 15:09

TerryA