Kee*_*nan 76 python dictionary list typeerror
我正试图拿一个看起来像这样的文件
AAA x 111
AAB x 111
AAA x 112
AAC x 123
...
Run Code Online (Sandbox Code Playgroud)
并使用字典,以便输出看起来像这样
{AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...}
Run Code Online (Sandbox Code Playgroud)
这就是我尝试过的
file = open("filename.txt", "r")
readline = file.readline().rstrip()
while readline!= "":
list = []
list = readline.split(" ")
j = list.index("x")
k = list[0:j]
v = list[j + 1:]
d = {}
if k not in d == False:
d[k] = []
d[k].append(v)
readline = file.readline().rstrip()
Run Code Online (Sandbox Code Playgroud)
我一直在接受TypeError: unhashable type: 'list'
.我知道字典中的键不能是列表,但我试图将我的值变成列表而不是键.我想知道我是否在某处犯了错误.
Roc*_*key 43
如其他答案所示,错误是由于k = list[0:j]
您的密钥转换为列表所致.您可以尝试的一件事是重新编写代码以利用该split
功能:
# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
d = {}
# Here we use readlines() to split the file into a list where each element is a line
for line in f.readlines():
# Now we split the file on `x`, since the part before the x will be
# the key and the part after the value
line = line.split('x')
# Take the line parts and strip out the spaces, assigning them to the variables
# Once you get a bit more comfortable, this works as well:
# key, value = [x.strip() for x in line]
key = line[0].strip()
value = line[1].strip()
# Now we check if the dictionary contains the key; if so, append the new value,
# and if not, make a new list that contains the current value
# (For future reference, this is a great place for a defaultdict :)
if key in d:
d[key].append(value)
else:
d[key] = [value]
print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用的是Python 3.x,则必须进行微调以使其正常工作.如果您打开文件rb
,则需要使用line = line.split(b'x')
(这可确保您使用正确类型的字符串拆分字节).您也可以使用with open('filename.txt', 'rU') as f:
(或甚至with open('filename.txt', 'r') as f:
)打开文件,它应该可以正常工作.
All*_*ітy 16
注意: 此答案未明确回答问题.其他答案都是这样做的.由于问题是特定于一个场景而且引发的异常是一般的,这个答案指向一般情况.
散列值只是整数,用于在字典查找过程中快速比较字典键.
在内部,hash()
方法调用__hash__()
对象的方法,默认情况下为任何对象设置.
>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为列表中的列表是一个无法进行哈希处理的列表.这可以通过将内部嵌套列表转换为元组来解决,
>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])
Run Code Online (Sandbox Code Playgroud)
>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506
Run Code Online (Sandbox Code Playgroud)
避免此错误的解决方案是重新构建列表以使嵌套元组而不是列表.
Jes*_*ame 15
您正在尝试使用k
(这是一个列表)作为键d
.列表是可变的,不能用作dict键.
此外,由于以下行,您永远不会初始化字典中的列表:
if k not in d == False:
Run Code Online (Sandbox Code Playgroud)
应该是:
if k not in d == True:
Run Code Online (Sandbox Code Playgroud)
实际应该是:
if k not in d:
Run Code Online (Sandbox Code Playgroud)
您收到unhashable type: 'list'
异常的原因是k = list[0:j]
设置k
为列表的“切片”,这在逻辑上是另一个通常较短的列表。你需要的是只得到列表中的第一项,像这样写k = list[0]
。对于从调用返回的列表的第三个元素v = list[j + 1:]
应该是相同的。v = list[2]
readline.split(" ")
我注意到代码中还有其他几个可能的问题,我将提及其中的几个。一个大的一个是你不希望(重新)初始化d
与d = {}
每一行的循环中读取。另一个是将变量命名为与任何内置类型相同的名称通常不是一个好主意,因为它会阻止您在需要时访问它们中的一个 - 并且对于习惯使用它的其他人来说会感到困惑指定这些标准项目之一的名称。出于这个原因,您应该将变量重命名为list
不同的名称,以避免出现此类问题。
这是你的一个工作版本,其中有这些更改,我还替换了if
你用来检查键是否已经在字典中的语句表达式,现在使用字典的setdefault()
方法来更简洁地完成同样的事情。
d = {}
with open("nameerror.txt", "r") as file:
line = file.readline().rstrip()
while line:
lst = line.split() # Split into sequence like ['AAA', 'x', '111'].
k, _, v = lst[:3] # Get first and third items.
d.setdefault(k, []).append(v)
line = file.readline().rstrip()
print('d: {}'.format(d))
Run Code Online (Sandbox Code Playgroud)
输出:
d = {}
with open("nameerror.txt", "r") as file:
line = file.readline().rstrip()
while line:
lst = line.split() # Split into sequence like ['AAA', 'x', '111'].
k, _, v = lst[:3] # Get first and third items.
d.setdefault(k, []).append(v)
line = file.readline().rstrip()
print('d: {}'.format(d))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
400981 次 |
最近记录: |