user3408267
user3408267

Reputation: 105

TypeError 'set' object does not support item assignment

I need to know why it won't let me increase the value of the assignment by 1:

keywords = {'states' : 0, 'observations' : 1, 'transition_probability' : 2, 'emission_probability' : 3}
keylines = {-1,-1,-1,-1}

lines = file.readlines()
for i in range(0,len(lines)):
    line = lines[i].rstrip()
    if line in keywords.keys():
        keylines[keywords[line]] = i + 1 << this is where it is giving me the error

I ran it as a class and it worked fine, but now as an in-line code piece it gives me this error.

Upvotes: 5

Views: 41866

Answers (2)

NireBryce
NireBryce

Reputation: 101

I'm surprised at the lack of answers here, so adding one that hits on one of the more common ways this manifests here in case anyone else hits this from Search and needs to know.

It's unclear if the OP is trying to use it as a set or a second dictionary, but in my case I encountered the error due to a common pitfall in Python.

It hinges on two things:

In Python, Dictionaries and sets both use { }. (as of python 3.10.2)

You cannot create a dictionary with only keys and no values. Due to this, if you just do a_dict = {1, 2, 3} you don't make a dict, you make a set, as shown in this example:

In [1]: test_dict = {1, 2, 3}
   ...: test_set = {1, 2, 3}
   ...:
   ...: print(f"{type(test_dict)=} {type(test_set)=}")

type(test_dict)=<class 'set'> 
type(test_set)=<class 'set'>

If you want to declare a dictionary with just it's keys, you'll add values to your key:value pairs. However, you can use None:

In [4]: test_dict = {1: None, 2: None, 3: None}
   ...: test_set = {1, 2, 3}
   ...:
   ...: print(f"{type(test_dict)=} {type(test_set)=}")
type(test_dict)=<class 'dict'> 
type(test_set)=<class 'set'>

or dict.fromkeys([1, 2, 3])

Upvotes: 10

Alex Hall
Alex Hall

Reputation: 36013

You're using a set, you want a list, which is created with square brackets:

keylines = [-1,-1,-1,-1]

Upvotes: 4

Related Questions