2013-07-15 48 views
2

所以我的文件看起来像这样:的Python - 创建从外部文本文件的字典

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

不使用'dict'作为变量名称,因为它是一个内置类型。改用'Dict'。 –

+0

@PeterVaro使用'dict'是不好的,你是对的。但'Dict'并不好多少​​;它意在表示一个类。 – glglgl

+1

@glglgl你是对的,如果我命名一个参数,我总是使用'dictionary'或'd',如果我用它作为'普通'变量,则使用一个冗长的名字。尽管使用CapitalCaseWords作为类是无关紧要的,但是一个约定。一个好的,我不得不说,但不是一个规则! –

回答

4

假设文件名为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'], 
... 
} 
0
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]) 
+1

'line.strip().span()'相当于'line.split()'只有后者更快更易读。 –

+0

谢谢。我将编辑它。@ InbarRose – zhangyangyu

1

一个非常有趣,优雅的解决方案:

>>> 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']})