1

I have am checking if a bunch of if statements are true, and if they are writing results to a nested dictionary. For example:

alex_age = 9
jim_age = 10
alex_fav_sport = "soccer"
jim_fav_sport = "b-ball"
jose_fav_animal = "dog"
jessie_fav_anmial = "zebra"
students_total = 75

out = {}
if alex_age != jim_age: 
    out['school'] = {}
    out['school']['students_data'] = {}
    out['school']['students_data']['4th Grade'] = {}
    out['school']['students_data']['4th Grade']['Student'] = {} 
    out['school']['students_data']['4th Grade']['Student']['Alex L'] = {}
    out['school']['students_data']['4th Grade']['Student']['Alex L']['age'] = {}
    out['school']['students_data']['4th Grade']['Student']['Alex L']['age'] = alex_age 

if alex_fav_sport != jim_fav_sport: 
    out['school'] = {}
    out['school']['students_data'] = {}
    out['school']['students_data']['4th Grade'] = {}
    out['school']['students_data']['4th Grade']['Student'] = {} 
    out['school']['students_data']['4th Grade']['Student']['Alex L']['Fav Sport'] = {}
    out['school']['students_data']['4th Grade']['Student']['Alex L']['Fav Sport'] = alex_fav_sport 

if students_total > 35: 
    out['school'] = {}
    out['school']['students_data'] = {}
    out['school']['students_data']['Total Students In School'] = {}
    out['school']['students_data']['Total Students In School'] = students_total 

if jose_fav_animal != jessie_fav_animal: 
    out['school'] = {}
    out['school']['students_data'] = {}
    out['school']['students_data']['2nd Grade'] = {}
    out['school']['students_data']['2nd Grade']['Student'] = {} 
    out['school']['students_data']['2nd Grade']['Student']['Jose F'] = {}
    out['school']['students_data']['2nd Grade']['Student']['Jose F']['Fav Animal'] = jose_fav_animal

How could I write a function that will create the nests based off my desired inputs?

orestisf
  • 1,396
  • 1
  • 15
  • 30
a_1995
  • 45
  • 6

1 Answers1

0

You can have a helper function like this:

out = {}
def create(*args):
    d = out
    for arg in args:
         d = d.setdefault(arg, {})

create('school', 'students_data', '4th Grade', 'Student', 'Alex L', 'age')
create('school', 'students_data', '4th Grade', 'Student', 'Alex L', 'Fav Sport')

Or it can take key-word only arguments for the last key,value pair:

def create(*args, k, v):
    d = out
    for arg in args:
         d = d.setdefault(arg, {})
    d[k] = v

create('school', 'students_data', '4th Grade', 'Student', 'Alex L', k='age', v=alex_age)
create('school', 'students_data', '4th Grade', 'Student', 'Alex L', k='Fav Sport', v="soccer")

Alternatively, you can use a nested default dict:

from collections import defaultdict

def rec_dd():
    return defaultdict(rec_dd)

out = rec_dd()
out['school']['students_data']['4th Grade']['Student']['Alex L']['age'] = alex_age
orestisf
  • 1,396
  • 1
  • 15
  • 30