python 多层级对象 内容更新

2019-06-13  本文已影响0人  牛奶大泡芙

json文件的层级不确定,key参数用“.”隔开,把value内容添加到key指定的位置,可以更新config(dict)对象

def update_config(config, key, value):
    """
    update config
    :param config:
    :param key:
    :param value:
    :return:
    """
    ks = key.split(".")
    value = value.strip()
    temp=config
    for index,key in enumerate(ks):
        if(key not in temp):
            temp[key]={}
        if index<len(ks)-1: 
            temp=temp[key]   
    if isinstance(temp[key],list):
        temp[key].append(value) 
    else:           
        temp[key]=value    
上一篇 下一篇

猜你喜欢

热点阅读