【问题标题】:Getting type error when modifying the values in a dictionary修改字典中的值时出现类型错误
【发布时间】: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


【解决方案1】:

我修改了你的代码,试试这个:

client_dict = {'client 1':['ABC', 'EFG'], 'client 2':['MNO','XYZ'], 'client 3':['ZZZ']}

x = input('Enter the client name:\n')
print(client_dict[x])
y = input('if ok enter y otherwise enter n:\n')
if y == 'n':
    for i in range(len(client_dict[x])):
        client_dict[x][i] = input('enter the correct header:\n')
else: 
    pass

抱歉,现在试试这个。 已编辑

【讨论】:

  • 编辑了您的答案,因为您根本不需要 lst 变量。
  • 是的,我编辑了这个。现在它工作正常
【解决方案2】:

我认为您不小心将值分配给了 client_dict 中的键。如,您试图说一个值,列表,是它出错的行上的新条目中的键。您可能想要执行以下操作:

client_dict["client1"] = x 但将“client1”替换为代表该客户名称的变量。您可能错误地认为 x 是您的客户端的名称(又名 key),但实际上它等于此字典条目的 value,因为这行:

x = client_dict[input('Enter the client name:\n')] 这就是说“当我进入字典“client_dict”并访问键(input()调用的结果)所在的位置时,将 x 分配给结果值”

通过 kvp 写出您的字典的含义可能会有所帮助:

键应该是:字符串

值应该是:列表

然后,检查您的代码并考虑所有内容的类型。这是 Python 的一个问题,因为它很容易混淆每个变量应该表示的类型,因为它是动态类型的

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 2016-10-13
    • 2014-02-14
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2013-04-04
    相关资源
    最近更新 更多