Python Forum
Looping to Create Nested Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping to Create Nested Dictionary
#7
import re

out='''1 assignment_1 85 100 0.25
2 test_1 90 100 0.25
3 exam_1 95 100 0.5'''
innerdict = {}
outerdict = {}
parts_1 = out.split("\n")
for line in parts_1:
    
    parts = line.split(" ")
    line_tuple = (int(parts[0]), parts[1], int(parts[2]), int(parts[3]), float(parts[4]))
    key = line_tuple[1]
    outerdict[key] = dict(innerdict)
    outerdict[key]={'Total':'{0}'.format(parts[3]),'Number':'{0}'.format(parts[0]),'Grade':'{0}'.format(parts[2]),'Weight':'{0}'.format(parts[4])}
    
  
print(outerdict)

output:


Output:
{'assignment_1': {'Total': '100', 'Number': '1', 'Grade': '85', 'Weight': '0.25'}, 'test_1': {'Total': '100', 'Number': '2', 'Grade': '90', 'Weight': '0.25'}, 'exam_1': {'Total': '100', 'Number': '3', 'Grade': '95', 'Weight': '0.5'}}
You can try this.
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 wavic - Dec-16-2017, 09:54 AM
RE: Looping to Create Nested Dictionary - by swarup19 - Jun-22-2018, 04:56 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,600 Nov-03-2020, 08:32 AM
Last Post: DeaD_EyE
  how can i create a dictionary of dictionaries from a file Astone 2 2,368 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  nested looping with list cap510 2 2,005 Sep-10-2020, 04:51 AM
Last Post: cap510
  nested dictionary Maxime 3 3,687 Mar-14-2019, 07:19 AM
Last Post: perfringo
  Looping through a dictionary for every other value fad3r 15 9,924 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