<p>试试这个代码</p>
<p>它还支持多个级别的组合</p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Tuple
def iterate_multilevel_dictionary(d: dict):
dicts_to_iterate: List[Tuple[dict, list]] = [(d, [])]
'''
the first item is the dict object and the second object is the prefix keys
'''
while dicts_to_iterate:
current_dict, suffix = dicts_to_iterate.pop()
for k, v in current_dict.items():
if isinstance(v, dict):
dicts_to_iterate.append((v, suffix + [k]))
else:
yield suffix + [k] + [v]
if __name__ == '__main__':
d_level1 = {"a": 1, "b": 2, "c": 3}
print(f"test for {d_level1}")
for items in iterate_multilevel_dictionary(d_level1):
print(items)
d_level2 = {"group_1": {"a": 1}, "group_2": {"b": 2, "c": 3}}
print(f"test for {d_level2}")
for items in iterate_multilevel_dictionary(d_level2):
print(items)
d_level3 = {"collection_1": d_level2}
print(f"test for {d_level3}")
for items in iterate_multilevel_dictionary(d_level3):
print(items)
d_level123 = {}
[d_level123.update(i) for i in [d_level1, d_level2, d_level3]]
print(f"test for {d_level123}")
for items in iterate_multilevel_dictionary(d_level123):
print(items)
</code></pre>
<p>产出是:</p>
<pre><code>test for {'a': 1, 'b': 2, 'c': 3}
['a', 1]
['b', 2]
['c', 3]
test for {'group_1': {'a': 1}, 'group_2': {'b': 2, 'c': 3}}
['group_2', 'b', 2]
['group_2', 'c', 3]
['group_1', 'a', 1]
test for {'collection_1': {'group_1': {'a': 1}, 'group_2': {'b': 2, 'c': 3}}}
['collection_1', 'group_2', 'b', 2]
['collection_1', 'group_2', 'c', 3]
['collection_1', 'group_1', 'a', 1]
test for {'a': 1, 'b': 2, 'c': 3, 'group_1': {'a': 1}, 'group_2': {'b': 2, 'c': 3}, 'collection_1': {'group_1': {'a': 1}, 'group_2': {'b': 2, 'c': 3}}}
['a', 1]
['b', 2]
['c', 3]
['collection_1', 'group_2', 'b', 2]
['collection_1', 'group_2', 'c', 3]
['collection_1', 'group_1', 'a', 1]
['group_2', 'b', 2]
['group_2', 'c', 3]
['group_1', 'a', 1]
</code></pre>
<p>使用递归是另一种方法,但我认为不使用递归的写作更具挑战性和效率:)</p>