python - 将文本文件读取为 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
解决方案
这很简单。请参阅下面的代码。
dictionary = {}
with open("text.txt", "r") as file:
for lines in file:
line = lines.split()
dictionary[line[0]] = line[1:]
print(dictionary)
推荐阅读
- javascript - 创建一个 google 脚本,用于在电子表格的每一页上的同一单元格中查找和替换文本
- clickhouse - Clickhouse 中物化视图的工作原理
- python - RuntimeError:张量的元素 0 不需要 grad 并且没有用于非神经网络实现的 grad_fn
- traefik - 使用 traefik 查看超过 :80 的 traefik 仪表板
- python - 我看不到是什么触发了无效的语法错误
- python - 创建一个上传按钮并将文件作为变量读取
- unreal-engine4 - Hololens Emulator:虚幻引擎应用完全黑,但 Win64 可以工作
- javascript - 纯 JavaScript - 仅更新整个 Html 表中的一个单元格
- pine-script - 在 Pine Script 中无法正确绘制历史最高记录
- java - Java Swing如何在JPanel中显示图形组件