python - 如何通过读取 .txt 文件为每个键创建具有多个 'lists' 的 Python 字典?

标签 python dictionary

我有一个大文本文件,如下所示:

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:
   ....

由于字典的格式略有不同(它在上面的 for 循环中期望 3 个值,但接收到的值超过 3 个),我无法用我当前的代码执行此操作,但是它可以使用第一种字典格式。

任何人都可以建议解决这个问题吗?

最佳答案

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)))

编辑:由于您希望键也为整数,因此您可以在拆分值上映射 int 函数,如下所示

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

关于python - 如何通过读取 .txt 文件为每个键创建具有多个 'lists' 的 Python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39807586/

相关文章:

python - PySide2 QDialog 可能存在的错误

python - 合并来自多个excel的一张表的数据

python - 使用cython来早期类型化类属性

swift - 使用枚举键向 Swift 字典添加值

r - 使用 R 开发地理专题图

python - pip安装python-lzo时找不到文件报错

ios - 如何将字典作为参数附加到 URL?

python - 从多个字典写入单个 CSV 文件

java - 如何将条目放入 map ?

python - pyramid_mailer 主题标题问题