Get a list of all keys in nested dictionary

前端 未结 3 823
遇见更好的自我
遇见更好的自我 2021-01-15 12:13

I want to get a list of all keys in a nested dictionary that contains lists and dictionaries.

I currently have this code, but it seems to be missing adding some keys

3条回答
  •  借酒劲吻你
    2021-01-15 12:35

    This should do the job:

    def get_keys(dl, keys_list):
        if isinstance(dl, dict):
            keys_list += dl.keys()
            map(lambda x: get_keys(x, keys_list), dl.values())
        elif isinstance(dl, list):
            map(lambda x: get_keys(x, keys_list), dl)
    

    To avoid duplicates you can use set, e.g.:

    keys_list = list( set( keys_list ) )
    

    Example test case:

    keys_list = []
    d = {1: 2, 3: 4, 5: [{7: {9: 1}}]}
    get_keys(d, keys_list)
    print keys_list
    >>>> [1, 3, 5, 7, 9]
    

提交回复
热议问题