所以我做了大量的谷歌搜索,但仍然无法解决这个问题。 我试过这个:
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])] = []
答案 0 :(得分:1)
空格在这里不是一个好的分隔符,因为列表的字符串表示包含一个空格。对于我的回答,我正在使用'|'作为分隔符。
要加载csv文件以使其创建与您编写的dict相同的dict,您可以使用以下内容:
try:
reader = csv.reader(open('bar.in', 'rb'), delimiter='|')
result = dict((int(x[0]), eval(x[1])) for x in reader)
print "testcsv.csv found, load it from file."
except:
print "testcsv.csv not found. loop all over."
所以现在的结果是:
{4441: [4441, 4442], 4442: [4441, 4442]}
所有数字都是整数。但请记住,这使用eval,而eval可能很危险。
答案 1 :(得分:1)
这有效(并且不使用eval()
)。请注意,编写csv文件行的方式与您的版本略有不同。
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) # note difference from your version
try:
reader = csv.reader(open('testcsv.csv', 'rb'), delimiter=' ')
result = dict((row[0], row[1:]) for row in (map(int, row) for row in reader))
print "testcsv.csv found, load it from file."
print result
except Exception as e:
print "testcsv.csv not found. loop all over."
print e
输出:
testcsv.csv found, load it from file.
{4441: [4441, 4442], 4442: [4441, 4442]}
注意:创建result
的单行代码相当于:
result = {}
for row in (map(int, row) for row in reader):
result[row[0]] = row[1:]
答案 2 :(得分:0)
您需要有一个扁平的列表,例如[a,b,c...]
而不是[a,[...],c,...]
for key, value in mydict.items():
writer.writerow([key]+ value)
将输出(第一行)
4441 4441 4442