创建嵌套字典的更好方法?

时间:2020-07-11 23:30:33

标签: python dictionary nested

我正在检查一堆if语句是否为真,以及它们是否将结果写入嵌套字典中。例如:

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

我该如何编写一个函数,根据期望的输入来创建嵌套?

1 个答案:

答案 0 :(得分:0)

您可以具有如下帮助功能:

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')

或者它可以只接受关键字参数作为最后一个键值对:

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")

或者,您可以使用nested默认字典:

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