TomKo
TomKo

Reputation: 1

"TypeError: 'type' object does not support item assignment" when trying to use dictionaries

This is a very basic snippet adder/viewer/remover. The way I want it to work, the user would enter a name (dictionary key) and then the text body (value of key), to add entries. For example- "Testsnippet" which is the key for the value "This is a test text snippet."

I don't know what's wrong with it. Trying to use the "add/modify" option lets me enter the snippet text I want to enter as the key's value, but it gives me this error: TypeError: 'type' object does not support item assignment

In addition, trying to use the remove option just gives me the add/modify option, not the remove option. Using "view" works fine.

from sys import exit

clip_list = {'test':'whatever, this is a test'}

breaker = "--------------------"

while True:
    print "What do you want to do?"
    print "[view] [add/modify] [remove] [quit]"

    action = raw_input("> ")

    if action == "view":
        view_choice = raw_input("Enter snippet name to view OR type 'all' for the entire list:\n> ")
        if view_choice == 'all':
            print clip_list
            print breaker
        else:
            print clip_list[view_choice]
            print breaker

    elif action == "add" or "modify":
        snippet_name = raw_input("Enter snippet name:\n> ")
        snippet_input = raw_input("Text:\n> ")
        dict[str(snippet_name)] = str(snippet_input)
        print "Added!"

    elif action == "remove":
        snippet_name = raw_input("Enter snippet name to remove:\n> ")
        del dict[snippet_name]
        print "Deleted!"

    elif action == "quit":
        print "Goodbye!"
        exit(0)

    else:
        print "What? Please enter a valid command!"

Upvotes: 0

Views: 22219

Answers (3)

Ben
Ben

Reputation: 71450

With that code, you'll find that any command other than "view" does the add/modify action. The reason is your add or modify condition:

    elif action == "add" or "modify":

You are joining two conditions with or, so that the overall condition is true if either one of the sub-conditions is true. The first condition is action == "add", which is true if action is equal to "add". The condition on the other side of the or though is just "modify". Any non-empty string is considered to be true in an if statement, so this condition is always true. It should be:

    elif action == "add" or action == "modify":

Upvotes: 0

Pikaurd
Pikaurd

Reputation: 1124

I agree with Ignacio Vazquez-Abrams you should using your global dict clip_list. BTW: your action remove should modify too. del clip_list[snippet_name] or clip_list.pop(snippet_name)

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798636

I think you meant clip_list[str(snippet_name)] wherever you wrote dict[str(snippet_name)]. But if all the keys and values are the same then you should be using a set instead.

Upvotes: 1

Related Questions