python 存储字典路径实现访问及修改值

存在以下需求,由于某个字典嵌套太多层,有太多的键,需要读取字典多个键的值,与输入比较,然后对多个键重新设置值。

我们假设字典如下:

kidshair = {'allkids':{'child1':{'hair':'blonde'},
                      'child2':{'hair':'black'},
                      'child3':{'hair':'red'},
                      'child4':{'hair':'brown'}}}

如果读取的时候通过普通读取字典的方式,那么嵌套太多层的字典,就需要写两次路径,会格外的长,显得很冗余。

if   kidshair['allkids']['child3']['hair'] = **:
        kidshair['allkids']['child3']['hair'] = $$

因此考虑将每个字典的键的路径保存下来,读和写的时候只需要调用路径这个变量就可。

使用Storing dictionary path in Python - Stack Overflow  里提到的办法

def pathGet(dictionary, path):
    for item in path.split("/"):
        dictionary = dictionary[item]
    return dictionary

def pathSet(dictionary, path, setItem):
    path = path.split("/")
    key = path[-1]
    dictionary = pathGet(dictionary, "/".join(path[:-1]))
    dictionary[key] = setItem
>>> pathGet(kidshair, "allkids/child1/hair")
'blonde'
>>> pathSet(kidshair, "allkids/child1/hair", "blue")
>>> kidshair['allkids']['child1']
{'hair': 'blue'}

这样我们可以将路径 allkids/child1/hair存在变量中,如下,即可通过只写一次路径,实现读和写字典。

path='allkids/child1/hair'
pathGet(kidshair, path)
pathSet(kidshair, path, "blue")

2、以上方法仅适用与字典,对于字典中包含列表不适用,新增兼容路径中存在列表的方法,修改

pathGet函数

    def pathGet(self,dictionary, path):
        for item in path.split("/"):
            if  "["   in  item:  #兼容路径字符串里面  /log/[2]/disk中 [2]取列表
                item = eval(item)[0]
            dictionary = dictionary[item]
        return dictionary

 对于一些请求,需要先获取参数,然后修改众多参数其中之一,可以采用以下方法

    def  modify_one_wlan_message(self,wlan_ssid,**kwargs):
        wlan_one_data = self.get_one_wlan_message(wlan_ssid)["data"]
        wlan_id = wlan_one_data["id"]

        if kwargs.__contains__("role_limit_count"):
                role_limit_count_path = "advanceopt/account_limit/role_limit/[0]/count"
                self.pathSet(wlan_one_data, role_limit_count_path,kwargs["role_limit_count"])



        request_payload ={"opr":"modify","data":wlan_one_data,"id":wlan_id}
        print(request_payload)
        data = self.post(request_payload)
        return    data

先获取参数得到wlan_one_data,然后判断kwargs传入的参数是否存在,存在则修改对应路径的值

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值