Arun
Arun

Reputation: 1679

Python assign a dictionary to a dictionary

I'm new to python, and new to python dicitonaries

I have a loop, which reads names of books and assigns them to a dictionary. I then assign them to another dictionary based on isbn:


book = {};
booklist = {};

for line in file.readlines():
    #parse file and assign to dict book
    ...
    isbn=splitline[0];
    title=splitline[1]
    description=splitline[2]      
    pubdate=splitline[3];
    author=splitline[4]
    ...
    book["isbn"]=isbn    
    book["title"]=title;
    book["description"]=description;
    book["pubdate"]=pubdate;
    book["author"]=author;
    ...

    booklist[isbn] =book;

When I run it, I see that booklist has the same books. Keys are correct isbn, but the book dictionary are all the last book! When I step through it, I can seek the dictionary book has the correct values. But when after the code completes, all the keys in booklist are assigned to the last book that was parsed. any suggestion son how I can make booklist point to the correct books?

Upvotes: 0

Views: 1717

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599590

You don't define a new book dictionary inside the loop, so each time through the loop you're just reusing the same dictionary over and over: and you just end up assigning the same one to multiple keys.

Instead, make sure you define a new book dict at the start of each iteration:

booklist = {}
for line in file:
    book = {}
    ...
    booklist['isbn'] = book

Upvotes: 4

Related Questions