Home > Enterprise >  Too many values to unpack: for loop with nested dictionaries
Too many values to unpack: for loop with nested dictionaries

Time:05-01

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?

CodePudding user response:

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