所以我做了很多谷歌搜索,但仍然无法解决这个问题。我试过这个:
import csv
mydict={4442:[4441,4442], 4441:[4441,4442]}
with open('testcsv.csv','wb') as f:
writer = csv.writer(f, delimiter=' ')
for key, value in mydict.items():
writer.writerow([key, value])
但这完全不是我所期望的。因为它会生成一个 csv 文件,例如:
4441 "[4441, 4442]"
4442 "[4441, 4442]"
我永远不会将字典值读取为列表而是字符串。我的阅读过程是这样的:
result={}
try:
reader = csv.reader(open('testcsv.csv', 'rb'))
result = dict(x for x in reader) #note: Everything turned to be string after reading from csv
print "testcsv.csv found, load it from file."
except:
print "testcsv.csv not found. loop all over."
然后我的结果变为:
print result
print result[str(4442)]
print result[str(4441)]
{'4441': '[4441, 4442]', '4442': '[4441, 4442]'}
[4441, 4442]
[4441, 4442]
所以我的问题是如何写/读一个以整数列表为值的字典?
更新解决方案,下面接受的答案也将起作用:
for row in reader:
if row[1][1:-1] != '':
result[int(row[0])] = map(int, row[1][1:-1].split(','))
else:
result[int(row[0])] = []