Tukanoid
Tukanoid

Reputation: 81

TypeError: list indices must be integers or slices, not str dictionary python

Here's the code:

with open("input.txt", "r") as f:
text = f.read()

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
res = {}
kol = 0
for buk in alphabet:
    if buk in text:
        kol += 1

if kol > 0:
    for bukwa in text:
        if bukwa in alphabet:
            if bukwa not in res:
                res[bukwa.upper()] = text.count(bukwa)
        elif bukwa not in alphabet:
            if bukwa not in res:
                res[bukwa.upper()] = 0
    res = sorted(res)

    with open("output.txt", "w") as f:
        for key in res:
            f.write(key + " " + str(res[key]))

if kol == 0:
    with open("output.txt", "w") as f:
        f.write(-1)

And here's the error:

Traceback (most recent call last):
  File "/home/tukanoid/Desktop/ejudge/analiz/analiz.py", line 23, in     <module>
    f.write(key + " " + str(res[key]))
TypeError: list indices must be integers or slices, not str

Upvotes: 2

Views: 11070

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

The line:

res = sorted(res)

isn't returning what you think it is. Using sort on a dictionary will sort its keys and return them as a list.

When you do res[key] inside the context manager, you're indexing the list with a string, resulting in an error.

If you want ordering in your dictionary you can do it in one of two ways:

Rename the list you create:

sorted_keys = sorted(res)

and then iterate through those while indexing the still referencing to the dict name res.

or, use OrderedDict and then iterate through its members as you would with a normal dict:

from collections import OrderedDict

# -- skipping rest of code --

# in the context manager
for key, val in OrderedDict(res):
    # write to file

Upvotes: 3

Related Questions