我有像這樣包含項列出的清單和值:讓嵌套的字典,unflatten
[
['mounts:device', '/dev/sda3'],
['mounts:fstype:[0]', 'ext1'],
['mounts:fstype:[1]', 'ext3']
]
那麼我可以列表中很容易地改變這個
(名單的arent分隔「:」)
[
['mounts:device', '/dev/sda3'],
['mounts:fstype[0]', 'ext1'],
['mounts:fstype[1]', 'ext3']
]
任何適合對於這個問題更好:
問題是創建一個字典:
{
'mounts': {
'device': '/dev/sda3',
'fstype': [
'ext1',
'ext3'
]
}
它也應該可以在列表中列出了例如:
['mounts:test:lala:fstype[0][0]', 'abc']
或
['mounts:test:lala:fstype:[0]:[0]', 'abc']
這是我到目前爲止有:基於
def unflatten(pair_list):
root = {}
for pair in pair_list:
context = root
key_list = pair[0].split(':')
key_list_last_item = key_list.pop()
for key in key_list:
if key not in context:
context[key] = {}
context = context[key]
context[key_list_last_item] = pair[1]
return root
這個回答https://stackoverflow.com/a/18648007/5413035,但根據要求,我需要recursivness和列表中的組合
預先感謝
什麼問題?請參閱:[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask) –
問題是如何實現unlatlatten到嵌套字典下面的函數不工作的列表 – Skeec
列表示例中的列表應該是什麼樣的字典?請[編輯]你的問題,並告訴我們。 – martineau