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:
"Message=too many values to unpack (expected 2)"
This is the line in question:

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"]] = {}
askedLanguage = input("What language? ")
if askedLanguage not in dictByLang:
    print("Not a valid language")
    for key,val in dictByLang[askedLanguage]:
        print(key, val['auth'], val['type'],val['sold'])

Thanks for your help!

>Solution :

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

Leave a Reply