我有一个大的文本文件,它看起来像:如何通过读取.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 ),但它可以使用第一个字典格式。
任何人都可以提出无论如何解决这个问题?
使用defaultdict http://stackoverflow.com/questions/27088835/access-multiplevalue -against-1-duplicating-key/27088919#27088919 –
你可以修复你的格式吗......你的缩进遍布各处。 – AChampion
更好? @achampion – aboublemc