【发布时间】:2022-01-23 02:25:21
【问题描述】:
我制作了以下字典:
client_dict = {'client 1':['ABC', 'EFG'], 'client 2':['MNO','XYZ'], 'client 3':['ZZZ']}
我想:从用户那里获取输入,显示客户端的值,如果可以,保持字典的当前状态,如果不是,用户可以更改给定客户端的值。为此,我做了以下操作:
x = client_dict[input('Enter the client name:\n')]
print(x)
y = input('if ok enter y otherwise enter n:\n')
if y =='n':
lst = []
for i in range(len(x)):
x[i] = input('enter the correct header:\n')
lst.append(x[i])
client_dict[x] = lst
else:
pass
假设在第一个输入中我输入client 1,然后输入n,这意味着我想更改值。然后,算法要求我两次输入所需的标头(因为客户端 1 有两个值),第一个标头我写 hello,第二个我写 world。阵容如下:
Enter the client name:
client 1
['ABC', 'EFG']
if ok enter y otherwise enter n:
n
enter the correct header:
hello
enter the correct header:
world
我现在可以检查我的client_dict,它被修改为:
{'client 1': ['hello', 'world'],
'client 2': ['MNO', 'XYZ'],
'client 3': ['ZZZ']}
这意味着代码做了我想要的,但是当条件语句中的过程结束时,我也收到以下错误:
TypeError: unhashable type: 'list'
来自:client_dict[x] = lst。所以我想知道我做错了什么?尽管代码有效,但在重写字典时似乎存在一些问题?
【问题讨论】:
-
这是因为 x 是一个列表,而列表是不可散列的,因此不能用作字典键
-
你应该做
x = input('Enter the client name:\n')。这样x保存的是键(即名称)而不是值(即标题列表)
标签: python list dictionary if-statement typeerror