从文件创建字典

时间:2015-08-10 09:48:50

标签: python file dictionary

该文件包含:

1 2
2 6
2 3
2 4
3 1
3 4
4 5
5 4
6 5
6 7
7 6
7 8
8 5
8 7

因此必须按如下方式创建字典:

D = {1: [2], 2: [6,3,4], 3: [1,4], 4: [5], 5: [4], 6: [5,7], 7: [6,8], 8: [5,7]}

行中的第一个元素是键。 什么是最有效的方式?

3 个答案:

答案 0 :(得分:5)

这应该做你想要的:

from __future__ import print_function

from collections import defaultdict

dict_from_file = defaultdict(list)

with open('yourfile.txt', 'r') as infile:
    for line in infile:
        key, value = [int(x) for x in line.split()]
        dict_from_file[key].append(value)

# The dictionary dict_from_file is in the format that you want
print(dict_from_file)

答案 1 :(得分:2)

您可以使用setdefault method方法

在没有collections模块的情况下执行此操作

<强>码

Inp_file = open('data.txt')
result = {}
for line in Inp_file.readlines():
     key, value = line.strip('\n').split(' ')
     result.setdefault(int(key),[]).append(int(value))

print(result)

<强>输出:

{1: [2], 2: [6,3,4], 3: [1,4], 4: [5], 5: [4], 6: [5,7], 7: [6,8], 8: [5,7]}

答案 2 :(得分:1)

你可以这样做: -

import collections

file = open('data.txt')
result = collections.defaultdict(list)
for line in file.readlines():
   key, value = line.strip('\n').split(' ')
   result[key].append(value)

print(result)