[
[壓縮嵌套詞典:壓縮密鑰
嵌套詞典,您需要通過每個密鑰對使用當前密鑰來串起一個新的鍵,從 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