python-3.x - 从 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 错误的地方。
解决方案
只需稍微改变逻辑,您就可以轻松实现所需的输出:
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
推荐阅读
- sql - SQL - 如何根据条件插入表中?
- angular - Angular 5:如何为数据绑定属性编写 Jasmine 单元测试
- symfony - Symfony,如何在实体中获取当前用户(FOS),未使用的__construct()?
- c# - 将不同的条件传递给 linq where
- excel - 如何在数据验证列表中搜索数字?
- python - Python,为“if object”语句调用了哪个魔术方法
- entity-framework - 如何在 EntityFrameworkCore InMemory 中包含对象属性
- xml - 如何在 Eclipse 中像打开 XML 一样打开文件
- javascript - 如何检查我的扩展程序是否安装在访问特定网页的浏览器上?
- sql-server - 两个新列 SQL Server:一个带有记者 ID,一个带有每行记者数