class GetResponsePara(object):
# 获取字典中的某一个键的值
def dict_get(self, dic, locators, default=None):
if not isinstance(dic, dict) or not isinstance(locators, list):
return default
value = None
for locator in locators:
if not type(value) in [dict, list] and isinstance(locator, str) and not self.can_convert_to_int(locator):
try:
value = dic[locator]
except KeyError:
return default
continue
if isinstance(value, dict):
try:
value = self.dict_get(value, [locator])
except KeyError:
return default
continue
if isinstance(value, list) and self.can_convert_to_int(locator):
try:
value = value[int(locator)]
except IndexError:
return default
continue
return value
def can_convert_to_int(self, input):
try:
int(input)
return True
except BaseException:
return False
# 获取字典中的某一个键的值(只支持结果是唯一值)(如果键对应的值是list只会取到其中的一个值)
def get_para2(self, response, key, path):
output = path.split('.')
for m in output:
if isinstance(response, dict):
if key in response:
print('==========', response[key])
return response[key]
response = response[m]
else:
for n in response:
if key in n:
return n[key]
def chaiparam(self, output):
list = []
mn = output.split(';')
print(mn)
for i in mn:
ban = i.split('=')
list.append(ban)
print(dict(list))
return dict(list)
if __name__ == '__main__':
p = GetResponsePara()
dict_test = {"result": {"code": "110002", "msg": [{'status': 'ok'}, {'status': 'failed'}]}}
result = p.dict_get(dict_test, ['result', 'msg', '1', 'status'])
print(result)
dict_test = {"statusCode": 0, "message": "success", "data": {"token": "2C8A41292D428", "onlyUser": 2}}
result = p.dict_get(dict_test, ['data', 'token'])
print(result)
response = {"statusCode":0,"message":"success","data":[{"id":213},{"id":214}]}
key = 'id'
path = 'data.id'
print(p.get_para2(response, key, path))
output = 'token=data.token'
print(p.chaiparam(output))
Python+获取字典中某一个键的值
于 2022-04-15 13:37:17 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)