所以我的文件看起来像这样:
0 1
0 2
0 34
0 67
1 98
1 67
1 87
2 23
2 45
2 98
...
等等。我的问题是,我怎样才能从这个文本文件中制作一个看起来像这样的字典:
dict = {'0':['1', '2', '34', '67']
'1':['98', '67', '87']
'2':['23', '45', '98']
'3':['x','x','x']}
所以我的文件看起来像这样:
0 1
0 2
0 34
0 67
1 98
1 67
1 87
2 23
2 45
2 98
...
等等。我的问题是,我怎样才能从这个文本文件中制作一个看起来像这样的字典:
dict = {'0':['1', '2', '34', '67']
'1':['98', '67', '87']
'2':['23', '45', '98']
'3':['x','x','x']}
假设文件被称为test.txt
:
from collections import defaultdict
import csv
data = defaultdict(list)
with open("test.txt", "r") as f:
reader = csv.reader(f, delimiter=" ")
for row in reader:
data[row[0]].append(row[1])
那么data
值将是:
{
'0': ['1', '2', '34', '67'],
'1': ['98', '67', '87'],
'2': ['23', '45', '98'],
...
}
一个非常有趣且优雅的解决方案:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> with open(external_file) as f:
map(lambda x: d[x[0]].append(x[1]), map(str.split, f))
>>> d
defaultdict(<type 'list'>, {'1': ['98', '67', '87'], '0': ['1', '2', '34', '67'], '2': ['23', '45', '98']})
from collections import defaultdict
res = defaultdict(list)
with open(file) as f:
for line in f:
temp = line.split()
res[temp[0]].append(temp[1])