python基础-dict嵌套

dic = {
    'name':['twiss','iran','taibai'],
    'py9':{
        'time':'1213',
        'learn_money':19800,
        'addr':'CBD',
           },
    'age':21
}
# dic['age'] = 56
# print(dic['name'])
# dic['name'].append('ritian')
# l = [1,2,'twiss']
# l[2] = l[2].upper()
# dic['name'][1] = dic['name'][1].upper()
# print(dic)

#female : 6
# dic['py9']['female'] = 6
# print(dic)

# fhdklah123rfdj12fdjsl3    '       123     12    13'
info = input('>>>').strip()
for i in info:
    if i.isalpha():
        info = info.replace(i," ")
l = info.split()
print(len(l))

根据用户输入的展开dict嵌套depth层数,做展开数据

def dict_generator(indict, pre=None,depth=None):
    pre = pre[:] if pre else []
    if depth is None: depth=1
    if isinstance(indict, dict):
        for key, value in indict.items():
            if depth>1:
                if isinstance(value, dict):
                    if len(value) == 0:
                        yield pre+[key, '{}']
                    else:
                        for d in dict_generator(value, pre + [key],depth=depth-1):
                            yield d
                elif isinstance(value, list):
                    if len(value) == 0:
                        yield pre+[key, '[]']
                    else:
                        for v in value:
                            for d in dict_generator(v, pre + [key],depth=depth-1):
                                yield d
                elif isinstance(value, tuple):
                    if len(value) == 0:
                        yield pre+[key, '()']
                    else:
                        for v in value:
                            for d in dict_generator(v, pre + [key],depth=depth-1):
                                yield d
                else:
                    yield pre + [key, value]
            else:
                yield pre + [key, value]
    else:
        yield indict
def show_composite_dict(composite_json):
    for i in  composite_json:
        composite_key = '.'.join(i[0:-1])
        composite_value = i[-1]
        result_json = str(composite_key) + ":" + str(composite_value)
        print(result_json)

你可能感兴趣的:(Python)