如其他答案所示,错误是由于造成的
k = list[0:j],您的密钥被转换为列表。您可以尝试做的一件事是重新编写代码以利用该
split功能:
# Using with ensures that the file is properly closed when you're donewith 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']}请注意,如果您使用的是Python 3.x,则必须稍作调整才能使其正常运行。如果使用打开文件
rb,则需要使用
line =line.split(b'x')(确保使用正确的字符串类型分割字节)。您也可以使用
with open('filename.txt', 'rU') asf:(甚至with open('filename.txt', 'r') as f:)打开文件,它应该可以正常工作。


