我有這個嵌套的 python 字典
dictionary = {'a':'1', 'b':{'c':'2', 'd':{'z':'5', 'e':{'f':'13', 'g':'14'}}}}
所以推薦的輸出將是:
output = ['a:1', 'b:c:2', 'b:d:z:5', 'b:d:e:f:13', 'b:d:e:g:13']
使用recursive function和不使用遞回函式
uj5u.com熱心網友回復:
在這種情況下,我總是喜歡先嘗試解決簡單的部分。
def flatten_dict(dictionary):
output = []
for key, item in dictionary.items():
if isinstance(item, dict):
output.append(f'{key}:???') # Hm, here is the difficult part
else:
output.append(f'{key}:{item}')
return output
現在嘗試flatten_dict(dictionary)列印['a:1', 'b:???']顯然不夠好。一方面,該串列中的三個專案太少了。
首先,我想改用生成器函式。這現在更復雜,但稍后會得到回報。
def flatten_dict(dictionary):
return list(flatten_dict_impl(dictionary))
def flatten_dict_impl(dictionary):
for key, item in dictionary.items():
if isinstance(item, dict):
yield f'{key}:???'
else:
yield f'{key}:{item}'
輸出還沒有變化。是時候去恢復了。
您希望輸出是一個平面串列,這意味著我們必須在item字典的情況下產生多個東西。只是,什么東西?讓我們嘗試flatten_dict_impl在這個子字典上插入一個遞回呼叫,這似乎是最直接的方法。
# flatten_dict is unchanged
def flatten_dict_impl(dictionary):
for key, item in dictionary.items():
if isinstance(item, dict):
for value in flatten_dict_impl(item):
yield f'{key}:{value}'
else:
yield f'{key}:{item}'
輸出現在是['a:1', 'b:c:2', 'b:d:z:5', 'b:d:e:f:13', 'b:d:e:g:14'],這是您想要的輸出,除了最后 14 個,但我認為這是您的錯字。
Now the non-recursive route. For that we need to manage some state ourselves, because we need to know how deep we are.
def flatten_dict_nonrecursive(dictionary):
return list(flatten_dict_nonrecursive_impl(dictionary))
def flatten_dict_nonrecursive_impl(dictionary):
dictionaries = [iter(dictionary.items())]
keys = []
while dictionaries:
try:
key, value = next(dictionaries[-1])
except StopIteration:
dictionaries.pop()
if keys:
keys.pop()
else:
if isinstance(value, dict):
keys.append(key)
dictionaries.append(iter(value.items()))
else:
yield ':'.join(keys [key, value])
Now this gives the right output but is a lot less easy to understand, and a lot longer. It took a lot longer for me to get right too. There may be shorter and more obvious ways to do it that I missed, but in general recursive problems are easier to solve with recursive functions.
Such an approach can still be useful: if your dictionaries are nested hundreds or thousands of levels deep, then trying to do it recursively will likely overflow the stack.
I hope this helps. Let me know if I need to go into more detail or something.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/425219.html
下一篇:即使在使用遞回時追加也得到空串列
