Python Forum
Looping to Create Nested Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping to Create Nested Dictionary
#5
Let's go back to your initial code and initial output
        outerdict[key] = innerdict 
 
        innerdict["number"] = line_tuple[0]
        innerdict["grade"] = line_tuple[2]
        innerdict["total"] = line_tuple[3]
        innerdict["weight"] = line_tuple[4]
From the output, we see that we have the right data of the third record, three times. This is "normal" because, as I said, the keys of outerdict point to innerdict and not its hard values.

Let's slightly reorganize the code by first populating innerdict, then assign it to the outerdict:
        innerdict["number"] = line_tuple[0]
        innerdict["grade"] = line_tuple[2]
        innerdict["total"] = line_tuple[3]
        innerdict["weight"] = line_tuple[4]

        outerdict[key] = innerdict 
And finally, how to tell python to copy the hard values of innerdict? You can use the following way:
        outerdict[key] = dict(innerdict) 
(Note: to be fully correct, this statement is OK for making a copy of a "simple" dictionary which itself doesn't contain any complex objects like a list or a dictionary. For such cases, do a research on "copy" and "deepcopy")
Reply


Messages In This Thread
Looping to Create Nested Dictionary - by gngu2691 - Dec-15-2017, 10:29 PM
RE: Looping to Create Nested Dictionary - by wavic - Dec-15-2017, 11:04 PM
RE: Looping to Create Nested Dictionary - by squenson - Dec-16-2017, 06:15 AM
RE: Looping to Create Nested Dictionary - by wavic - Dec-16-2017, 09:54 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  create empty sets for keys in a dictionary and add values to the set naughtysensei 1 2,555 Nov-03-2020, 08:32 AM
Last Post: DeaD_EyE
  how can i create a dictionary of dictionaries from a file Astone 2 2,308 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  nested looping with list cap510 2 1,964 Sep-10-2020, 04:51 AM
Last Post: cap510
  nested dictionary Maxime 3 3,631 Mar-14-2019, 07:19 AM
Last Post: perfringo
  Looping through a dictionary for every other value fad3r 15 9,665 Jan-25-2018, 07:12 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020