I have a list:
lst = [[1,0],[20,0],[21,1],[22,3],[24,2]]
Also a dict
dct = {0:"Balco",1:"Greg",2:"Palm",3:"New"}
I want to replace the 2nd element of nested list with the values that match from the dictionary.
So, the expected new list will be:
lst = [[1,"Balco"],[20,"Balco"],[21,"Greg"],[22,"New"],[24,"Palm"]]
A simple for
loop should work:
for item in lst:
item[1] = dct[item[1]]
print(lst)
Or, using list comprehension for a one-liner:
result = [[item[0], dct[item[1]]] for item in lst]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.