0

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
danny30
  • 19
  • 3

3 Answers3

1

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:

  1. Pre-process your input, e.g. a list of pairs [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5), ('six', 6)].
  2. Remove the incompatible indices.
  3. Use a tool to build a dictionary from pairs, e.g. 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}
pylang
  • 40,867
  • 14
  • 129
  • 121
1

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}
alvas
  • 115,346
  • 109
  • 446
  • 738
0

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]})
jpp
  • 159,742
  • 34
  • 281
  • 339
  • I did some research and found the collections mod. I will apply that in the furture. Thank you for the response. – danny30 Feb 10 '18 at 19:45
  • @danny30, that's great. feel free to upvote or accept (tick on left) so others know this works. – jpp Feb 10 '18 at 19:47