Python,如何使用文件中的行作为字典中的键,使用下一行作为值?

标签 python file dictionary

我有这样一个文件:

   Ben
   0 1 5 2 0 1 0 1
   Tim
   3 2 1 5 4 0 0 1

我想制作一本如下所示的字典:

    {Ben: 0 1 5 2 0 1 0 1, Tim : 3 2 1 5 4 0 0 1}

所以我在想:

   for line in file:
       dict[line] = line + 1

但是你不能像那样遍历文件,所以我该怎么做 做这个?

最佳答案

这可能是您想要的:

dict_data = {}
with open('data.txt') as f:
    for key in f:
        dict_data[key.strip()] = next(f).split()

print dict_data

输出:

{'Tim': ['3', '2', '1', '5', '4', '0', '0', '1'], 'Ben': ['0', '1', '5', '2', '0', '1', '0', '1']}

讨论

  • for 循环假定每一行都是一个键,我们将读取循环体中的下一行
  • key.strip() 将 'Tim\n' 转换为 'Tim'
  • f.next() 读取并返回下一行——关键行之后的行
  • f.next().split() 因此将该行拆分为一个列表
  • dict_data[key.strip()] = ... 会做类似的事情:dict_data['Tim'] = [ ... ]

更新

  • 感谢 Blckknght 的指点。我将 f.next() 更改为 next(f)

更新2

如果你想把列表变成一个整数列表而不是字符串,那么代替:

        dict_data[key.strip()] = next(f).split()

这样做:

        dict_data[key.strip()] = [int(i) for i in next(f).split()]

关于Python,如何使用文件中的行作为字典中的键,使用下一行作为值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909699/

相关文章:

python - SQLAlchemy:在内部格式和数据库格式之间来回转换列值

python - 仅在 Slurm 中提交 python 作业时出错

用于创建和显示所有字母组合的 Python 程序,从字典中的不同键中选择每个字母

Python:列表字典理解

斯卡拉 : Merge two immutable maps on key and get new immutable map with same type

python - django rest 框架 - 使用 View 集

python - 为什么 Django 没有查看权限?

objective-c - 打开文件 - cocoa

dup2 上的困惑

python - 使用输入文件对象从python中的文件中读取变量