Reputation: 49
Create a new list with the first element of each nested list replaced with the corresponding value from the dictionary. Assume all objects will be keys present in dictionary.
d = {'A': 'Orange',
'B': 'Apples',
'C': 'Bananas'}
l = [['A', 'Foo', 'Bar'],
['A', 'Bar', 'Foo'],
['B', 'Frog', 'Mouse'],
['C', 'Owl', 'Ant'],
['C', 'Foo', 'Bar']]
Goal:
[['Orange', 'Foo', 'Bar'],
['Orange', 'Bar', 'Foo'],
['Apples', 'Frog', 'Mouse'],
['Bananas', 'Owl', 'Ant'],
['Bananas', 'Foo', 'Bar']]
repl = [d[x[0] for x in l]
for i in range(len(l)):
l[i][0] = repl[i]
Looking to receive feedback and improvements to the way that I went about solving this task. My solution definitely operates under the assumption that the ordering of the nested list will not change, but I would like to get feedback from others and bolster the solution for edge-cases.
Upvotes: 0
Views: 640
Reputation: 4238
This works:
In [28]: d = {'A': 'Orange',
...: 'B': 'Apples',
...: 'C': 'Bananas'}
...:
...:
...: l = [['A', 'Foo', 'Bar'],
...: ['A', 'Bar', 'Foo'],
...: ['B', 'Frog', 'Mouse'],
...: ['C', 'Owl', 'Ant'],
...: ['C', 'Foo', 'Bar']]
In [31]: for item in l:
...: item[0] = d[item[0]]
The benefit is that the code accomplishes the work in a single loop over the input data.
Python for
loops do not require that you calculate the length, thus there is no reason for you to calculate the range(len)
value.
Similarly, since the for
loop automatically references each item in the data using the target variable (here I am calling it item
) then we can reference any element in the item (i.e. using item[0]
).
Upvotes: 2
Reputation: 75
Keeping your original code, all you need to do is add an extra ]
to the first line.
repl = [d[x[0]] for x in l]
for i in range(len(l)):
l[i][0] = repl[i]
Upvotes: 1