Python - 从外部文本文件创建字典

时间:2013-07-15 11:12:57

标签: python file dictionary

所以我的文件看起来像这样:

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

3 个答案:

答案 0 :(得分: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'],
 ...
}

答案 1 :(得分: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']})

答案 2 :(得分: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])
相关问题