首页 > 解决方案 > 为什么以下用于将扁平字典转换为嵌套字典的代码有效?

问题描述

我来自 JavaScript 背景,在我的一生中,我无法理解为什么来自geeksforgeeks的这个 python 代码示例有效。

输入数据:

{'Geeks_for_for':1,'for_geeks_Geeks':3,'geeks_Geeks_for':7}

输出:

{'Geeks': {'for': {'for': 1}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks': {'for': 7}}}

代码:

def insert(dct, lst):
    for x in lst[:-2]:
        dct[x] = dct = dct.get(x, dict())
        print(x)
        print(dct)
    dct.update({lst[-2]: lst[-1]})
    print("---######---")
    print(dct)

def convert_nested(dct):
    result = dict()
    lsts = [[*k.split("_"), v] for k, v in dct.items()]
    for lst in lsts:
        insert(result, lst)
    print(result)

ini={'Geeks_for_for':1,'for_geeks_Geeks':3,'geeks_Geeks_for':7}
convert_nested(ini)

打印输出:

Geeks
{}
for
{}
---######---
{'for': 1}
for
{}
geeks
{}
---######---
{'Geeks': 3}
geeks
{}
Geeks
{}
---######---
{'for': 7}
{'Geeks': {'for': {'for': 1}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks': {'for': 7}}}

我的理解是, dct[x] = dct = dct.get(x, dict()) 将空值初始化为键(例如使用 try catch 来“分配”空值)。但同时它也破坏了 dct 对象。那么它是如何保存的呢?或者是这样,python 只允许更改字典值但不允许破坏键?如果这是有道理的:(。有人可以给我逐行解释插入函数的 2 行吗?

标签: pythondictionary

解决方案


Python从左到右分配,所以

dct[x] = dct = dct.get(x, dict())

就好像

subdict = dct.get(x, dict())  # get subdict or new one when missing
dct[x] = subdict              # save subdict (needed only when missing)
dct = subdict                 # continue with the subdict

除非没有额外的变量。在我看来这是一种愚蠢的写作方式

dct = dct.setdefault(x, {})

dct.update({lst[-2]: lst[-1]})在我看来,这是一种愚蠢的写作方式dct[lst[-2]] = lst[-1]

嗯,这就是你尝试从我的经验可怕的 geeksforgeeks 中学习 Python 的结果。


推荐阅读