Python: Dynamically update a dictionary with varying variable “depth”

后端 未结 1 1157
悲哀的现实
悲哀的现实 2021-01-26 17:13

I have a dictionary with various variable types - from simple strings to other nested dictionaries several levels deep. I need to create a pointer to a specific key:value pair s

相关标签:
1条回答
  • 2021-01-26 17:54

    The hard part here is to know whether an index must be used as a string form a mapping of as an integer for a list.

    I will first try to process it as an integer index on a list, and revert to a string index of a mapping in case of any exception:

    def update_batman_db(key, value):
        keys = key.split('-')  # parse the received key
        ix = batman_db         # initialize a "pointer" to the top most item
        for key in keys[:-1]:  # process up to the last key item
            try:               #  descending in the structure
                i = int(key)
                ix = ix[i]
            except:
                ix = ix[key]
        try:                   # assign the value with last key item
            i = int(keys[-1])
            ix[i] = value
        except:
            ix[keys[-1]] = value
    
    0 讨论(0)
提交回复
热议问题