1

所以我做了很多谷歌搜索,但仍然无法解决这个问题。我试过这个:

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])] = []
4

3 回答 3

1

空格在这里不是一个好的分隔符,因为列表的字符串表示包含空格。对于我的回答,我使用的是 '|' 作为分隔符。

要加载 csv 文件以创建与您编写的相同的 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 可能很危险。

于 2013-07-17T03:22:00.920 回答
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:]
于 2013-07-17T04:04:59.983 回答
0

你需要有一个扁平的列表,比如[a,b,c...]not[a,[...],c,...]

for key, value in mydict.items():
    writer.writerow([key]+ value)

将输出(第一行)

4441 4441 4442
于 2013-07-17T03:04:38.530 回答