how to make nested dictionary in python

Question:

I want to make a nested dictionary but I don’t know why I am not getting my desired result

def stud(data):
    empty_dic = {}
    for line in data:
       empty_dic[line["stud_num"]]={line[course]:line[marks]}
    return empty_dic
data = [
  {
   
    "course": "asd",
    "stud_num": "123",
    "marks": 28
  },
  {
    
    "course": "qrt",
    "stud_num": "123",
    "marks": 27
  },
  {
 "course": "asd",
    "stud_num": "124",
    "marks": 30
  },
  {
   "course": "zx",
    "stud_num": "124",
    "marks": 31
  },
  {
   "course": "zx",
    "stud_num": "123",
    "marks": 28
  }
]

output of my code is => {"123":{"zx":28},"124":{"zx":31}}

my desired output is => {"123":{"asd":28,"qrt":27,"zx":28},124:{"asd":30,"zx":31}}

Asked By: Ejaz

||

Answers:

Use can simply do it by using collections.defaultdict:

from collections import defaultdict

adict = defaultdict(dict)
for obj in data:
    adict[obj['stud_num']][obj["course"]] = obj['marks']

print(adict)

Your fixed version (assgin empty dict if there’s no line["stud_num"] in the empty_dic):

def stud(data):
    empty_dic = {}
    for line in data:
        if line["stud_num"] not in empty_dic:
            empty_dic[line["stud_num"]] = {}
        empty_dic[line["stud_num"]][line['course']] = line['marks']
    return empty_dic

Output:

{'123': {'asd': 28, 'qrt': 27, 'zx': 28}, '124': {'asd': 30, 'zx': 31}}
Answered By: funnydman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.