Reputation: 19
I am trying to move items from a list into a dictionary but I get the following error:
'int' object is not subscriptable
Here is my code:
l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
d = {}
for line in l_s:
if line[0] in d:
d[line[0]].append(line[1])
else:
d[line[0]] = [line[1]]
print(d)
How would I go about changing it?
Upvotes: 0
Views: 1585
Reputation: 44485
Why do you get an error?
In Python, that error typically means "You can't slice this object." Strings, lists, tuples, etc are sliceable, but integers are not. The error is raised during iteration as it comes across an integer.
Options
Depending on what results you want, here are some options to try:
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5), ('six', 6)]
.pip install more_itertools
.Solution
I suspect you want results similar to option 3:
import more_itertools as mit
lst = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
{k: v for k, v in mit.sliced(lst, 2)}
# {'five': 5, 'four': 4, 'one': 1, 'six': 6, 'three': 3, 'two': 2}
Upvotes: 1
Reputation: 122052
Something like this?
Using Way to iterate two items at a time in a list? and dictionary comprehension:
>> l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
>>> {k:v for k, v in zip(*[iter(l_s)]*2)}
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'five': 5, 'one': 1}
Upvotes: 1
Reputation: 164663
Use collections.defaultdict
, a subclass of dict
. This sets the default value for any key to an empty list and allows you to easily append. Below is a guess of what you are looking for:
from collections import defaultdict
l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
d = defaultdict(list)
for txt, num in zip(l_s[::2], l_s[1::2]):
d[txt].append(num)
# defaultdict(list,
# {'five': [5],
# 'four': [4],
# 'one': [1],
# 'six': [6],
# 'three': [3],
# 'two': [2]})
Upvotes: 0