因一些特殊需求需要以引數的形式獲取字典中特定的值,網上搜了一下並沒有特別好的實現(並沒有太認真去找~),所以自己實現了一個,以供大家參考:) 。
話不多說,直接上程式碼:
def dict_get(dic, locators, default=None):
'''
:param dic: 輸入需要在其中取值的原始字典 <dict>
:param locators: 輸入取值定位器, 如:['result', 'msg', '-1', 'status'] <list>
:param default: 進行取值中報錯時所返回的預設值 (default: None)
:return: 返回根據引數locators找出的值
'''
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 can_convert_to_int(locator):
try:
value = dic[locator]
except KeyError:
return default
continue
if isinstance(value, dict):
try:
value = dict_get(value, [locator])
except KeyError:
return default
continue
if isinstance(value, list) and can_convert_to_int(locator):
try:
value = value[int(locator)]
except IndexError:
return default
continue
return value
def can_convert_to_int(input):
try:
int(input)
return True
except BaseException:
return False
複製程式碼
Best Practice
好的我們來進行一次簡單的最佳實踐:)
if __name__ == '__main__':
dict_test = {"result": {"code": "110002", "msg": [{'status': 'ok'}, {'status': 'failed'}]}}
result = dict_get(dict_test, ['result', 'msg', '-1', 'status'])
print(result)
複製程式碼
下面是控制檯的輸出,大家可以看到輸出是符合預期結果的:)
failed
Process finished with exit code 0
複製程式碼
這次分享到此為止~ 我們有緣再見:)
版權宣告:本文為博主原創文章,歡迎大家轉載,但是要註明我的文章地址。 juejin.im/post/5cbeb1…