Python3将文件放入字典ValueError:没有足够的值可解包(预期2,得到1)

时间:2018-11-26 12:05:12

标签: python-3.x file dictionary

我的问题是如何将文本文件转换成字典 这是我的代码。而且我得到了错误ValueError:没有足够的值要解压(预期2,得到1)

And this is the txt file

filename = ("/users/Reza/Downloads/anyar.txt")

commands = {}
with open(filename) as fh:
for line in fh:
    command, description = line.strip().split(' ', 1)
    commands[command] = description.strip()

print(commands)

对不起我的英语。谢谢

The dictonary output of the coding must like below

1 个答案:

答案 0 :(得分:1)

由于第一个数据行中没有空格,并且数据应该用/而不是空格分开,因此您收到错误消息。要获得预期的输出,您可以使用下面的示例代码。

import re
filename = ("input_file.txt")
has_header = True
count = 1
commands = {}
with open(filename) as fh:
    for line in fh:
        if has_header == True and count == 1:
            count+=1
            continue
        nama, id, Jumlah = line.strip().split('/')
        commands['nama'] = commands.get('nama','') + nama.split('.')[1] + ','
        commands['id'] = commands.get('id','') + id.split(':')[1] + ','
        commands['Jumlah'] = commands.get('Jumlah','') + Jumlah.split(':')[1] + ','

print(commands)

示例输出:

{'nama': 'Detergent ,Sabun Mandi ,Pasta gigi ,', 'id': 'B001 ,B002 ,B003 ,', 'Jumlah': '500,300,400,'}