Too many values to unpack: for loop with nested dictionaries

I am trying to iterate through a nested dictionary using a for loop to display all the books in a certain language. I want it to display Title, author, Type, and the copies sold. I’m getting the following error on the last line:

too many values to unpack (expected 2)

The error is thrown on the line containing:

for key,val in dictByLang[askedLanguage]:

Here is the dictionary and the rest of the code.

books = {'A Tale of Two Cities': {'auth': 'Charles Dickens', 'Lang': 'English', 'Type': 'Historical Fiction', 'sold': '200000000'}, 'Don Quixote': {'auth': 'Miguel de Cervantes', 'Lang': 'Spanish', 'Type': 'Satire', 'sold': '500000000'}, 'The Lord of the Rings': {'auth': 'J. R. R. Tolkien', 'Lang': 'English', 'Type': 'Fantasy', 'sold': '150000000'}, 'The Alchemist': {'auth': 'Paul Coelho', 'Lang': 'Portuguese', 'Type': 'Fantasy', 'sold': '150000000'}, 'The Little Prince': {'auth': 'Antoine de Saint-Exupery', 'Lang': 'French', 'Type': 'Fantasy', 'sold': '140000000'}}
dictByLang = {}
for key, val in books.items():
    if val["Lang"] not in dictByLang:
       dictByLang[val["Lang"]] = {}
    dictByLang[val["Lang"]].update({key:val})            
askedLanguage = input("What language? ")
if askedLanguage not in dictByLang:
    print("Not a valid language")
else:
    for key,val in dictByLang[askedLanguage]:
        print(key, val['auth'], val['type'],val['sold'])

How can I fix this issue?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are two issues with your code:

  1. You need to iterate over dictByLang[askedLanguage].items(), rather than just dictByLang[askedLanguage] (which only iterates over the keys).
  2. The 'type' key in your for loop needs to have a capital T.

So, the for loop should look like the following:

for key, val in dictByLang[askedLanguage].items():
    print(key, val['auth'], val['Type'], val['sold'])


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x