python使用參數(shù)對嵌套字典進行取值的方法
更新時間:2019年04月26日 15:06:33 作者:泰斯特test
這篇文章主要介紹了python使用參數(shù)對嵌套字典進行取值,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
因一些特殊需求需要以參數(shù)的形式獲取字典中特定的值,網(wǎng)上搜了一下并沒有特別好的實現(xiàn)(并沒有太認真去找~),所以自己實現(xiàn)了一個,以供大家參考:) 。
話不多說,直接上代碼:
def dict_get(dic, locators, default=None): ''' :param dic: 輸入需要在其中取值的原始字典 <dict> :param locators: 輸入取值定位器, 如:['result', 'msg', '-1', 'status'] <list> :param default: 進行取值中報錯時所返回的默認值 (default: None) :return: 返回根據(jù)參數(shù)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
這次分享到此為止~ 我們有緣再見:)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python常用數(shù)據(jù)庫接口sqlite3和MySQLdb學習指南
在本章節(jié)中,我們將學習 Python 中常用的數(shù)據(jù)庫接口,包括 sqlite3用于SQLite數(shù)據(jù)庫和MySQLdb用于 MySQL 數(shù)據(jù)庫,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06Pandas統(tǒng)計計數(shù)value_counts()的使用
本文主要介紹了Pandas統(tǒng)計計數(shù)value_counts()的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07