Home > database >  how to make nested dictionary in python
how to make nested dictionary in python

Time:08-11

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}}

CodePudding user response:

Use can simply 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}}
  • Related