use*_*267 5 python dictionary set typeerror python-3.x
我需要知道为什么它不允许我将作业的值增加 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
Run Code Online (Sandbox Code Playgroud)
我将它作为一个类运行,它工作得很好,但现在作为一个内联代码片段,它给了我这个错误。
我对这里缺乏答案感到惊讶,因此添加一个符合此处表现形式的更常见方式之一的答案,以防其他人从搜索中找到此答案并需要知道。
目前尚不清楚 OP 是否尝试将其用作集合或第二个字典,但就我而言,由于 Python 中的常见陷阱,我遇到了错误。
这取决于两件事:
在Python中,字典和集合都使用{}。(从 python 3.10.2 开始)
您不能创建只有键而没有值的字典。因此,如果您只执行 a_dict = {1, 2, 3} 您不会创建一个字典,而是创建一个集合,如下例所示:
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'>
Run Code Online (Sandbox Code Playgroud)
如果您想声明一个仅包含键的字典,则可以将值添加到键:值对中。但是,您可以使用 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'>
Run Code Online (Sandbox Code Playgroud)
或dict.fromkeys ([1,2,3])
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           38100 次  |  
        
|   最近记录:  |