bhdrozgn
bhdrozgn

Reputation: 197

Replacing values in a list of lists with dictionary values, pythonic or better way

I have a dictionary like below:

my_dict = {'0123': 'apple',
           '2314': 'banana',
           '5214': 'cherry'}

And I have a list of lists like below:

my_list = [[0021, '0123', 10],
           [0025, '0123', 12],
           [0032, '2314', 8],
           [0045, '0123', 13],
           [0060, '5214', 12], 
           [0067, '2314', 10], ...]

I want to replace the values in the 1th index in lists in my_list with corresponding values from my_dict. I can achieve this with:

for number, fruit in my_dict.items():
    for i in range(len(my_list)):
        my_list[i][1] = my_list[i][1].replace(number, fruit)

And my output becomes:

[[0021, 'apple', 10],
 [0025, 'apple', 12],
 [0032, 'banana', 8],
 [0045, 'apple', 13],
 [0060, 'cherry', 12], 
 [0067, 'banana', 10], ...]

But I suppose this is not a great way to do it because it continues to iterate over already replaced values. It iterates over my_list as much as the key number in my_dict. Can we do this in a better way?

Upvotes: 0

Views: 486

Answers (1)

balderman
balderman

Reputation: 23815

just loop over the list and do a look up in the dict

my_list = [['0021', '0123', 10],
           ['0025', '0123', 12],
           ['0032', '2314', 8],
           ['0045', '0123', 13],
           ['0060', '5214', 12],
           ['0067', '2314', 10]]
my_dict = {'0123': 'apple',
           '2314': 'banana',
           '5214': 'cherry'}

for entry in my_list:
    entry[1] = my_dict.get(entry[1])
print(my_list)

output

[['0021', 'apple', 10], ['0025', 'apple', 12], ['0032', 'banana', 8], ['0045', 'apple', 13], ['0060', 'cherry', 12], ['0067', 'banana', 10]]

Upvotes: 2

Related Questions