Python:动态更新具有变化的变量“深度"的字典. [英] Python: Dynamically update a dictionary with varying variable "depth"

查看:89
本文介绍了Python:动态更新具有变化的变量“深度"的字典.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本具有各种变量类型的字典-从简单的字符串到其他嵌套的字典,深度达数个级别.我需要创建一个指向特定key:value对的指针,以便可以将其用于更新字典的函数中,并且可以这样调用:

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 so it can be used in a function that would update the dictionary and could be called like so:

dict_update(my_dictionary, value, level1key, *level2key....)

来自Web请求的数据如下:

Data coming from a web request like this:

data {
    'edited-fields': ['level1key-level2key-level3key', 'level1key-level2key-listindex', 'level1key'], 
    'level1key-level2key-level3key': 'value1', 
    'level1key-level2key-listindex': 'value2',
    'level1key': 'value3' 
}

我可以像这样读取原始值:

I can get to the original value to read it like this:

for field in data["edited-fields"]:
    args = field.split("-")
    value = my_dictionary
    for arg in args:
        if arg.isdigit():
            arg = int(arg)
        value = value[arg]
    print(value)

但是不知道如何使用相同的逻辑对其进行编辑.我无法用值本身进行搜索和替换,因为可能存在重复项,并且对于每个可能的arg计数都有多个if语句感觉不太pythonic.

But have no idea how to edit it using the same logic. I can't search and replace by the value itself as there can be duplicates and having several if statements for each possible arg count doesn't feel very pythonic.

示例:

data {
    'edited-fields': ['mail-signatures-work', 'mail-signatures-personal', 'mail-outofoffice', 'todo-pending-0'], 
    'mail-signatures-work': 'I'm Batman', 
    'mail-signatures-personal': 'Bruce, Wayne corp.',
    'mail-outofoffice': 'false',
    'todo-pending-0': 'Call Martha'
}

我想这样处理该请求:

for field in data['edited-fields']:
    update_batman_db(field, data[field])

def update_batman_db(key-to-parse, value):
    # how-to?
    # key-to-parse ('mail-signatures-work') -> batman_db pointer ["mail"]["signatures"]["work"] 
    # etc:
    batman_db["mail"]["signatures"]["work"] = value
    batman_db["mail"]["outofoffice"] = value # one less level
    batman_db["todo"]["pending"][0] = value # list index

推荐答案

这里的难点是要知道是否必须将索引用作字符串,并且必须将其映射为列表的整数.

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

这篇关于Python:动态更新具有变化的变量“深度"的字典.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆