首页 > 解决方案 > 如何展平嵌套的字典并在碰撞时使用内部值

问题描述

问题

对于以下字典:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

我想创建一个没有remove_meorworld键的新字典。

编辑更新:

总而言之,我想做以下事情:

如果项目的值是嵌套字典。使用内部结果更新新字典,同时从主字典中删除当前键值。

如果项目的值不是嵌套字典,则使用键值更新新字典。

接受的答案涵盖了这一点。

我尝试了什么?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

产量:

{'id': 1, 'label': 'hello'}

不完全是我需要的,因为我正在删除嵌套的字典。

期望的输出:

{'id': 1, 'label': 'hello','keep_me': 52}

标签: pythondictionaryflatten

解决方案


dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

# Just what you have done
new_dico = {k:v for (k,v) in dico.items() if not k == 'remove_me'}

# Plus this line
new_dico.update(dico['remove_me']['world'])

print(new_dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

受我在此处阅读的内容的启发,主 dict 的 flatten 函数,无论您的 key-dict 的深度是什么:

dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

def dFlatten(dico, d = {}):
    for k, v in dico.items():
        if isinstance(v, dict):
            dFlatten(v)
        else:
            d[k] = v
    return d
dico = dFlatten(dico)
print(dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

例如更深的 dico :

dico2 = {'id': 1, 'label': 'hello', 'stuff1': {'stuff2': {'remove_me': {'world': {'keep_me': 52}}}}}
dico2 = dFlatten(dico2)
print(dico2)         
# {'id': 1, 'label': 'hello', 'keep_me': 52}

具有多个具有相同 dFlatten 功能的深键

dico3 = {'id': 1, 'label': 'hello', 'deep': {'L1': {'L2': 52}}, 'remove_me': {'world': {'keep_me': 52}}}
dico3 = dFlatten(dico3)
print(dico3)         
# {'id': 1, 'label': 'hello', 'keep_me': 52, 'L2': 52}

推荐阅读