python - 为什么以下用于将扁平字典转换为嵌套字典的代码有效?
问题描述
我来自 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 行吗?
解决方案
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 的结果。
推荐阅读
- javascript - 更改 HTML 的 JavaScript 函数不起作用
- javascript - 如何循环/使用等待 axios?
- node.js - 获取存在嵌套键的 dynamodb 项目
- excel - Power 查询数据加载到模型和表中未正确排序
- react-select - React-select 自定义 Option 对象也不接收 innerprops.key
- amazon-web-services - CloudWatch 订阅过滤器:使用 lambda 或直接订阅
- go - 如何运行查询并以 csv 格式返回结果
- json - 规范化/展平非常深的嵌套 JSON(其中名称和属性在各个级别中相同)
- angular - 如何在使用以前的状态销毁 Angular 组件后恢复它
- c# - 苹果走出盒子,在最右边写着一个#。为什么?