簡體   English   中英

Python:動態更新具有變化的變量“深度”的字典

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

我有一本具有各種變量類型的字典-從簡單的字符串到其他嵌套的字典,這些字典的層次很深。 我需要創建一個指向特定key:value對的指針,以便可以將其用於更新字典的函數中,並且可以這樣調用:

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

來自網絡請求的數據如下:

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

我可以像這樣讀取原始值:

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。

例:

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

這里最難的部分是要知道是否必須將索引用作列表的整數映射形式的字符串。

我將首先嘗試將其作為列表上的整數索引處理,並在發生任何異常的情況下還原為映射的字符串索引:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM