Convert nested Python dict to object?

后端 未结 30 2413
时光取名叫无心
时光取名叫无心 2020-11-22 09:28

I\'m searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

30条回答
  •  青春惊慌失措
    2020-11-22 10:04

    I think a dict consists of number, string and dict is enough most time. So I ignore the situation that tuples, lists and other types not appearing in the final dimension of a dict.

    Considering inheritance, combined with recursion, it solves the print problem conveniently and also provides two ways to query a data,one way to edit a data.

    See the example below, a dict that describes some information about students:

    group=["class1","class2","class3","class4",]
    rank=["rank1","rank2","rank3","rank4","rank5",]
    data=["name","sex","height","weight","score"]
    
    #build a dict based on the lists above
    student_dic=dict([(g,dict([(r,dict([(d,'') for d in data])) for r in rank ]))for g in group])
    
    #this is the solution
    class dic2class(dict):
        def __init__(self, dic):
            for key,val in dic.items():
                self.__dict__[key]=self[key]=dic2class(val) if isinstance(val,dict) else val
    
    
    student_class=dic2class(student_dic)
    
    #one way to edit:
    student_class.class1.rank1['sex']='male'
    student_class.class1.rank1['name']='Nan Xiang'
    
    #two ways to query:
    print student_class.class1.rank1
    print student_class.class1['rank1']
    print '-'*50
    for rank in student_class.class1:
        print getattr(student_class.class1,rank)
    

    Results:

    {'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''}
    {'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''}
    --------------------------------------------------
    {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''}
    {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''}
    {'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''}
    {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''}
    {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''}
    

提交回复
热议问题