简体   繁体   中英

how to make nested dictionary in python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM