python - 从文本中将键和值读入Python dict

标签 python file dictionary

我有一个这种格式的文本文件。

the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658
and 0.26818 0.14346 -0.27877 0.016257 0.11384 0.69923 -0.51332 -0.47368 -0.33075 -0.13834 0.2702 0.30938 -0.45012 -0.4127 -0.09932 0.038085 

我想将它读入一个 python 字典变量,这样我就有了

{'the': [0.418, 0.24968,..], 'and': [0.26818 0.14346,..]}

我不知道如何开始?

最佳答案

这是一个有效的解决方案:

my_dict = {}
with open('your_file_name') as f:
    for line in f:
        elements = line.split()
        my_dict[elements[0]] = [float(e) for e in elements[1:]]

请注意,@CoryKramer 建议的解决方案使用 readlines,它返回一个列表而不是迭代器。所以我不建议对大文件使用他的解决方案(这会不必要地占用太多内存)。

关于python - 从文本中将键和值读入Python dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129512/

相关文章:

java - Apache Camel Message Exchange - 您能否迭代交换以从交换中的单个消息生成多个输出文件

c# - 复制字典的意外结果

python - 更快地将 int 转换为单个数字列表?

python - 无法使用 Conda 将 PyTorch 1.4.0 更新到 1.5.0

python - 使用 Pandas 检查值是否存在或新的

java NullPointerException 存在图像

Linux 命令 Cat 不要在文件夹中归档存档位存档

python - 使用 QTreeView 编辑字典

python - 反向 OrderedDict 类型错误

python - 列表索引超出范围,当我将范围 1 缩小时,它会丢失一项