python - 来自文本文件的字典

标签 python list dictionary

我有这个文本文件:

English 
hello bye 
italian 
ciao hola
spanish
hola chao

我想从每两行连续的行创建一个字典:

{
    'English': 'hello bye',
    'italian': 'ciao hola',
    'spanish': 'hola chao',
}

这是我的代码:

d= {}
with open("test.txt", 'r') as f:
    l = f.readlines()
    for line in l:
        (key,val) = line.split()
        d[key]=val

我收到错误:

too many values to unpack error

最佳答案

您还可以使用此方法:

d = {}
with open("test.txt", 'r') as f:
    l = f.readlines()
    i = 0
    while i < len(l):
        d[l[i].replace("\n","")] = l[i+1].replace("\n","")
        i += 2

关于python - 来自文本文件的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931246/

相关文章:

java - 从 Java 中的 List 中过滤重复的 Object 类型

python - python中包含列表的划分字典

python - 如何计算日期列表中的连续天数

python 文本小部件获取方法

python - 如何从位于数组顶部的多边形内的 NumPy 二维数组中提取值?

c# - 限项 list

python - 按第一项对嵌套列表进行排序——itemgetter 没有做到这一点

python - 在 Django 中调用 .delay() 后 celery 任务挂起

Python redis rpop 是 resultng b'value' 列表结构

Python - 遍历具有特定格式输出的列表列表;文件输出