存在以下需求,由于某个字典嵌套太多层,有太多的键,需要读取字典多个键的值,与输入比较,然后对多个键重新设置值。
我们假设字典如下:
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传入的参数是否存在,存在则修改对应路径的值