Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

python 3.x - ValueError When Reading dictionary from Txt File

I'm trying to read in a dictionary from a file, and extract its keys and values to print a string. When I try to print the current key and values, it says that there's too many values to unpack: expected 1 but got 2. I don't get why this would be occuring?

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

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

This is what I've got so far:

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()

Line 10 @ for key, value is where I'm getting a Value error.

question from:https://stackoverflow.com/questions/66057004/valueerror-when-reading-dictionary-from-txt-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With slight change in the logic, you may easily achieve the desired output:

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))

The generated output is as follows:

Violet CS307 CS422
Liam CS307
Amelia CS352
Finn CS422

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...