Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"]] = {}
    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'])

Thanks for your help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading