简体   繁体   中英

How to move items from a list into a dictionary

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?

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, eg 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, eg 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}

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}

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]})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM