簡體   English   中英

替換嵌套字典中的鍵

[英]Replace keys in a nested dictionary

我有一個嵌套字典{1: {2: {3: None}}}和一個將嵌套字典的鍵映射到一組值的字典,例如{1: x, 2: y, 3: z} 我想將嵌套字典轉換為這種形式{x: {y: {z: None}}} 我嘗試了幾個遞歸函數,但我一直在兜圈子,讓自己感到困惑。 實現這一目標的最佳方法是什么?

嵌套的層次是任意的。 以上是一個簡單的例子。

您需要在使用新鍵構建新字典時遞歸字典。 請注意,如果您在某處有一個列表或元組,其中包含其他字典,則不會處理它們 - 您必須添加一些代碼來執行此操作。 您實際上可以在不構建新字典的情況下執行此操作,但我認為這種方式更簡單。

od = { 1: { 2: { 3: None }}}
kd = { 1: 'x', 2: 'y', 3: 'z' }

def replace_keys(old_dict, key_dict):
    new_dict = { }
    for key in old_dict.keys():
        new_key = key_dict.get(key, key)
        if isinstance(old_dict[key], dict):
            new_dict[new_key] = replace_keys(old_dict[key], key_dict)
        else:
            new_dict[new_key] = old_dict[key]
    return new_dict

nd = replace_keys(od, kd)
print nd

輸出:

{'x': {'y': {'z': None}}}

接受的答案將不支持列表的字典,添加完整功能

@bilentor,

od = {'name': 'John', '1': [{'name': 'innername'}]}
kd = { 'name': 'cname', '1': '2', 3: 'z' }

def replace_keys(data_dict, key_dict):
    new_dict = { }
    if isinstance(data_dict, list):
        dict_value_list = list()
        for inner_dict in data_dict:
            dict_value_list.append(replace_keys(inner_dict, key_dict))
        return dict_value_list
    else:
        for key in data_dict.keys():
            value = data_dict[key]
            new_key = key_dict.get(key, key)
            if isinstance(value, dict) or isinstance(value, list):
                new_dict[new_key] = replace_keys(value, key_dict)
            else:
                new_dict[new_key] = value
        return new_dict
    return new_dict

nd = replace_keys(od, kd)
print(nd)

您可以使用NestedDict

from ndicts import NestedDict

d = {1: {2: {3: None}}}
replace = {1: 'x', 2: 'y', 3: 'z'}

def ndict_replace(ndict: dict, map: dict):
    nd = NestedDict(nd)
    new_nd = NestedDict()
    for key, value in nd.items():
        new_key = tuple(replace.get(k, k) for k in key)
        new_nd[new_key] = value
    return new_nd.to_dict()
>>> ndict_replace(d, replace)
{'x': {'y': {'z': None}}}

該解決方案是強大的,適用於任何嵌套字典

>>> d = {
        1: {2: {3: None}}, 
        3: {4: None},
        5: None
    }
>>> ndict_replace(d, replace)
{'x': {'y': {'z': None}}, 'z': {4: None}, 4: None}}

安裝ndicts pip install ndicts

暫無
暫無

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

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