首页 > 解决方案 > 将文本文件读取为 dict

问题描述

我的文本文件看起来像这样..每一行用空格分隔。

dream 4.345 0.456 6.3456
play 0.1223 -0.345 5.3543
faster 1.324 2.435 -2.2345

我想写字典并打印如下...

dream: [4.345 0.456 6.3456]
play: [0.1223 -0.345 5.3543]
faster: [1.324 2.435 -2.2345]

我的代码如下。请用这个纠正我...

with open("text.txt", "r") as file:
     for lines in file:
        line = lines.split()
        keys = b[0] 
        values = b[1:]
        d[keys] = values
print d

标签: pythonpython-3.x

解决方案


这很简单。请参阅下面的代码。

  dictionary = {}
  with open("text.txt", "r") as file:  
      for lines in file:
          line = lines.split()
          dictionary[line[0]] = line[1:]
  print(dictionary)

推荐阅读