首页 > 解决方案 > 从 Txt 文件中读取字典时出现 ValueError

问题描述

我正在尝试从文件中读取字典,并提取其键和值以打印字符串。当我尝试打印当前的键和值时,它说有太多的值需要解压:预期为 1 但得到了 2。我不明白为什么会发生这种情况?

Input: {'CS307': ['Violet', 'Liam'], 'CS352': ['Amelia'], 'CS422': ['Finn', 'Violet']}

Expected Output (as a string): 
Violet CS307 CS422
Liam CS307
Amelia CS352
Finn CS422

这是我到目前为止所得到的:

import ast

def reverse(filename, students):
newDict = {}
listOfStudents = []
with open(filename, 'r') as myFile:
    content = myFile.read()
    for line in content:
        newDict = ast.literal_eval(content)
    for key, value in newDict:
        print("Key:", newDict[key])
        listOfStudents.extend(newDict[key])
    print("All Students:", listOfStudents)

print(newDict)

myFile.close()

第 10 行 @ for key, value 是我收到 Value 错误的地方。

标签: python-3.xstringfiledictionaryfile-io

解决方案


只需稍微改变逻辑,您就可以轻松实现所需的输出:

import ast
from pathlib import Path

def reverse(filename):      # changed the parameters; students was unused
    newDict = {}
    listOfStudents = {}     # I changed this to a dictionary
    with open(filename, 'r') as myFile:
        content = myFile.read().strip()
        
        for line in content:
            newDict = ast.literal_eval(content)
            
        for key, value in newDict.items():    # you missd the .items(), which caused the "there's too many values to unpack" error
            for v in value:         # new logic from here
                if v in listOfStudents:
                    listOfStudents[v].append(key)
                else:
                    listOfStudents[v] = [key]
    return listOfStudents

string = reverse(str(Path(_path_to_your_text_file_)))   # change the path before executing

for k, v in string.items():
    print(k, ' '.join(v))

生成的输出如下:

Violet CS307 CS422
Liam CS307
Amelia CS352
Finn CS422

推荐阅读