[
[压缩嵌套词典:压缩密钥
嵌套词典,您需要通过每个密钥对使用当前密钥来串起一个新的键,从 underscore.Deeper levels of the nested dictionary require further recursion using the same process.
Once you've completed the recursion, create a new dictionary from the flattened items.
Here's an example implementation using Python's collections.abc.MutableMapping:
from collections.abc import mutableMapping def flatten(字典,parent_key ='',saparator ='_'): 项目= [] 对于键,dictionary.items()中的值: new_key = parent_key分隔键如果parent_key else键 如果Isinstance(值,mutablePapping): items.extend(flatten(value,new_key,saparator = saparator).items()) 别的: items.append((new_key,value)) 返回dict(items)
示例用法:>>> flatten({'a':1,'c':{'a':2,'b':{'x':5,'y':10}}},'d':[1,2,3]}) {'a':1,'c_a':2,'c_b_x':5,'d':[1,2,3],'c_b_y'':10}
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3