Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试替换字典中的数字(python)_Python_Python 3.x_Dictionary_Hashtable - Fatal编程技术网

尝试替换字典中的数字(python)

尝试替换字典中的数字(python),python,python-3.x,dictionary,hashtable,Python,Python 3.x,Dictionary,Hashtable,在我的代码中,我试图编写一些类似于哈希表的代码,我正在做的是在表中添加数字,有人能帮我吗?我的代码在这里: num = input("Number you want to insert:") table = {"1":0, "2":0, "3":0 } print(table) def insert(table): find_key = int(num) % len(table) # Linear probing? for i in range(len(table

在我的代码中,我试图编写一些类似于哈希表的代码,我正在做的是在表中添加数字,有人能帮我吗?我的代码在这里:

num = input("Number you want to insert:")
table = {"1":0, "2":0, "3":0 }
print(table)
def insert(table):
     find_key = int(num) % len(table)
      # Linear probing?
     for i in range(len(table)):            
        if i == find_key:
            dict[i] = int(num)
            print(table)
     print(i)
     return i
print(table)
insert(table)                 
错误是 TypeError:“type”对象不支持项分配

有一个输入错误:dict[…]=。。。应为表[…]=

您不需要自己实现哈希表。Python字典是哈希表

如果字典中有给定的关键项,那么简单地分配给字典就会添加或替换它

def insert(table, num):
     table[num] = int(num)  # not dict[...] = ...

num = input("Number you want to insert:")
table = {"1":0, "2":0, "3":0 }
print(table)  # before insert
insert(table, num)
print(table)  # after insert

你希望dict[i]=intnum能实现什么?dict是一种类型。您正在尝试分配给它,但这不起作用。dict已经是散列表了,所以不清楚您的目标是什么。。。应为表[i]=。。。。除此之外,不使用索引0、1、2。。要访问项,您需要使用键1、2、3。迭代字典将生成键!字典是哈希表。如果您打算自己实现一个,我建议您在想要实现哈希表时使用列表yourself@falsetru我正在尝试替换号码,而不是添加其他组。表[I]=。。。如果存在相同的密钥,将替换该项。