Pett zon
Pett zon

Reputation: 3

Python saving dictionarys in files. Problem with "TypeError: list indices must be integers or slices, not str"

I´m doing a phonebook thing for a project using the dictionarys. Everything has been going fine untill this problematic part where I save the newly added keys and values. I wonder where im doing wrong?


Katalog={"Edd":["4858"],
         "Zaa":["4202"],
          }

def save(Katalog):
    badChars = [",""[","]","'"]
    savelist=[]
    filname=input()
    f=open(filname,"w")
    for namn in Katalog:
        savelist.append(namn)
        savelist.append(":")

        for x in Katalog[namn]:
            savelist.append(Katalog[namn][x])
            savelist.append(":")
    savelist.append("\n")

    saveList = ''.join(i for i in saveList if not i in badChars)
    f.write(savelist)
    f.close()

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

Upvotes: 0

Views: 49

Answers (1)

Aemyl
Aemyl

Reputation: 2194

Katalog: Dict[str, List[str]]

for namn in Katalog:

namn is a key for Katalog

    for x in Katalog[namn]:

x is a string contained in Katalog[namn]

        savelist.append(Katalog[namn][x])

Katalog[namn] is the list which contains x, but using x as an index for it won't work. you could just change this line to savelist.append(x)

        savelist.append(":")

swap that line with the previous one, such that the separator is between key and value.

Instead of writing an own function, you could also use the json module from the standard library:

import json

def save(Katalog):

    with open(input(), "w") as f:
        josn.dump(Katalog, f)

Upvotes: 1

Related Questions