使用 yield from 递归 python 字典以生成嵌套字典键列表
Recursing python dictionaries with yield from to generate list of nested dictionary keys
我想为字典中的每个值生成一个唯一的嵌套键列表,这样:
input_dict = {"a": {"b": "c", "d": {"e": "f"}}, "f": "g"}
expected_result = [["a", "b"], ["a", "d", "e"], ["f"]]
我认为沿着这些思路的某些东西会起作用,将每个键附加到列表并递归直到达到一个值。在这一点上,我产生了一个列表并继续。
def _i(itr, list_of_keys):
if list_of_keys is None:
list_of_keys = []
if isinstance(itr, dict):
# For each dict, add the key to the list, and recurse
for key, value in itr.items():
list_of_keys.append(key)
yield from _i(value, list_of_keys)
else:
# If not a dict, then at the end of a series of keys, yield the list
yield list_of_keys
list_of_keys = []
然而当运行时,结果是所有唯一键
x = _i(input_dict, list_of_keys=None)
list(x)
[['a', 'b', 'd', 'e', 'f'],
['a', 'b', 'd', 'e', 'f'],
['a', 'b', 'd', 'e', 'f']]
我想我一定遗漏了一些关于 yield/input 参数如何工作的东西
您一直在修改同一个列表对象(最后重新分配局部变量对堆栈上下的任何递归调用都没有影响)!没有结转变量的更简单方法是:
def _i(obj):
if isinstance(obj, dict):
for k, v in obj.items():
for keys in _i(v):
yield [k] + keys
else:
yield []
>>> list(_i(input_dict))
[['a', 'b'], ['a', 'd', 'e'], ['f']]
我想为字典中的每个值生成一个唯一的嵌套键列表,这样:
input_dict = {"a": {"b": "c", "d": {"e": "f"}}, "f": "g"}
expected_result = [["a", "b"], ["a", "d", "e"], ["f"]]
我认为沿着这些思路的某些东西会起作用,将每个键附加到列表并递归直到达到一个值。在这一点上,我产生了一个列表并继续。
def _i(itr, list_of_keys):
if list_of_keys is None:
list_of_keys = []
if isinstance(itr, dict):
# For each dict, add the key to the list, and recurse
for key, value in itr.items():
list_of_keys.append(key)
yield from _i(value, list_of_keys)
else:
# If not a dict, then at the end of a series of keys, yield the list
yield list_of_keys
list_of_keys = []
然而当运行时,结果是所有唯一键
x = _i(input_dict, list_of_keys=None)
list(x)
[['a', 'b', 'd', 'e', 'f'],
['a', 'b', 'd', 'e', 'f'],
['a', 'b', 'd', 'e', 'f']]
我想我一定遗漏了一些关于 yield/input 参数如何工作的东西
您一直在修改同一个列表对象(最后重新分配局部变量对堆栈上下的任何递归调用都没有影响)!没有结转变量的更简单方法是:
def _i(obj):
if isinstance(obj, dict):
for k, v in obj.items():
for keys in _i(v):
yield [k] + keys
else:
yield []
>>> list(_i(input_dict))
[['a', 'b'], ['a', 'd', 'e'], ['f']]