Reputation:
This is my current snippet:
l = ['i', 'b', 'c', 'a', '3', 'a', '7', 'a', '9', 'k', 'a', '66', 'k', 'd']
new_list = []
a = {}
for i in range(len(l)):
if 'a' == l[i]:
a['plus_line'] = l[i+1]
new_list.append(a)
print(new_list)
I am expecting output like this below:
[{'plus_line': '3'}, {'plus_line': '7'}, {'plus_line': '9'}, {'plus_line': '66'}]
But I am getting:
[{'plus_line': '66'}, {'plus_line': '66'}, {'plus_line': '66'}, {'plus_line': '66'}]
I am trying to achieve when a
will be in the list, then the next item of the a
will be the value of the dict
.
Upvotes: 1
Views: 64
Reputation: 3988
See this:
>>> d = {}
>>> d['hi there'] = 23
>>> d['hi there'] = 24
>>> d
{'hi there': 24}
You're overwriting the key 'plus_line'
of dictionary a
.
Items you're appending in list new_list
are referencing to dictionary a
. Thus the problem.
Possible solution for that can be:
>>> new_list = []
>>> for i in range(len(l)):
... if 'a' == l[i] and i < len(l) - 2:
... new_list.append({'plus_line':l[i+1]})
...
>>> new_list
[{'plus_line': '3'}, {'plus_line': '7'}, {'plus_line': '9'}, {'plus_line': '66'}]
Upvotes: 0
Reputation: 2492
You simply needed to reset your a = {}
at the start of each loop (not outside the loop). By initializing it outside the loop, you created one dictionary named a
, which has only one key, plus line
which keeps getting assigned a new value.
l = ['i', 'b', 'c', 'a', '3', 'a', '7', 'a', '9', 'k', 'a', '66', 'k', 'd']
new_list = []
for i in range(len(l)):
a = {}
if 'a' == l[i]:
a['plus_line'] = l[i+1]
new_list.append(a)
print(new_list)
OUTPUT:
[{'plus_line': '3'}, {'plus_line': '7'}, {'plus_line': '9'}, {'plus_line': '66'}]
Upvotes: 0
Reputation: 1587
itzhaki explains the problem with your code, here's another possible way of doing it:
l = ['i', 'b', 'c', 'a', '3', 'a', '7', 'a', '9', 'k', 'a', '66', 'k', 'd']
result = [{'plus_line':l[n+1]} for n, i in enumerate(l) if i == 'a']
print(result)
Output:
[{'plus_line': '3'},
{'plus_line': '7'},
{'plus_line': '9'},
{'plus_line': '66'}]
Upvotes: 2
Reputation: 840
Your problem is that you're mutating the dict
named a
.
Instead you could do something like:
l = ['i', 'b', 'c', 'a', '3', 'a', '7', 'a', '9', 'k', 'a', '66', 'k', 'd']
new_list = []
for i in range(len(l)):
if 'a' == l[i]:
new_list.append({'plus_line': l[i+1]})
print(new_list)
This will create a new dict
instead of mutating an existing one.
Upvotes: 4