2016-10-01 61 views
3

我有一个大的文本文件,它看起来像:如何通过读取.txt文件为每个键创建多个'列表'的Python字典?

1 27 21 22 
1 151 24 26 
1 48 24 31 
2 14 6 8 
2 98 13 16 
. 
. 
. 

,我想创建一个字典。每个列表中的第一个数字应该在字典中的关键,应该是这种格式:

{1: [(27,21,22),(151,24,26),(48,24,31)], 
2: [(14,6,8),(98,13,16)]} 

我有以下代码(总点是在文本文件中的第一列中的最大数(即在字典中最大的键)):

from collections import defaultdict 

info = defaultdict(list) 
filetxt = 'file.txt' 
i = 1 

with open(filetxt, 'r') as file: 
    for i in range(1, num_cities + 1): 
     info[i] = 0 
    for line in file: 
     splitLine = line.split() 
     if info[int(splitLine[0])] == 0: 
      info[int(splitLine[0])] = ([",".join(splitLine[1:])]) 
     else: 
      info[int(splitLine[0])].append((",".join(splitLine[1:]))) 

其输出

{1: ['27,21,22','151,24,26','48,24,31'], 
2: ['14,6,8','98,13,16']} 

我想这样做词典的原因是因为我想通过每一个“内运行一个for循环清单”的字典对于给定的关键:

for first, second, third, in dictionary: 
    .... 

我不能与我当前的代码做,因为字典的格式稍有不同的这种(预计3个值在for循环以上,但收到超过3 ),但它可以使用第一个字典格式。

任何人都可以提出无论如何解决这个问题?

+0

使用defaultdict http://stackoverflow.com/questions/27088835/access-multiplevalue -against-1-duplicating-key/27088919#27088919 –

+0

你可以修复你的格式吗......你的缩进遍布各处。 – AChampion

+0

更好? @achampion – aboublemc

回答

4
result = {} 
with open(filetxt, 'r') as f: 
    for line in f: 
     # split the read line based on whitespace 
     idx, c1, c2, c3 = line.split() 

     # setdefault will set default value, if the key doesn't exist and 
     # return the value corresponding to the key. In this case, it returns a list and 
     # you append all the three values as a tuple to it 
     result.setdefault(idx, []).append((int(c1), int(c2), int(c3))) 

编辑:既然你要钥匙也为整数,则可以map在拆分值的int功能,这样

 idx, c1, c2, c3 = map(int, line.split()) 
     result.setdefault(idx, []).append((c1, c2, c3)) 
+4

'从集合中导入defaultdict',然后'result = defaultdict(list)'只允许'result [idx] .append(...)',因为任何键的列表都是保证存在的。 – 9000

+0

@ 9000我已经使用了defaultdict,但它仍然没有给出正确的输出。请参阅我更新的代码。 – aboublemc

3

要转换的值返回以逗号分隔的字符串,您不能在for first, second, third in data中使用 - 因此只需将它们作为列表splitLine[1:](或转换为tuple)即可。
您不需要初始化for循环与defaultdict。您也不需要使用defaultdict进行条件检查。

你没有多余的代码代码:

with open(filetxt, 'r') as file: 
    for line in file: 
     splitLine = line.split() 
     info[int(splitLine[0])].append(splitLine[1:]) 

,如果你想在int s运行我就转换了前一个细微的差别是:

with open(filetxt, 'r') as file: 
    for line in file: 
     splitLine = list(map(int, line.split())) # list wrapper for Py3 
     info[splitLine[0]].append(splitLine[1:]) 

其实在PY3,我会做:

 idx, *cs = map(int, line.split()) 
     info[idx].append(cs) 
相关问题