从给定的嵌套字典中,找到所有嵌套的键序列
From a given nested dictionary, find all the nested keys sequences
我有一个嵌套字典,如下所示:
dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}
我想提取列表格式的所有键序列,直到达到最深的 key:value 对。
预期的输出是这样的:
["A->AA", "A->BB->BBB", "A->BB->CCC"]
我尝试的解决方案是:
for k, v in dct.items():
if isinstance(v, dict):
# traverse nested dict
for x in find_keys(v):
yield "{}_{}".format(k, x)
print("{}_{}".format(k, x))
else:
yield k
print(k)
但它似乎没有按预期工作。
我猜你已经差不多了(或错误地省略了一些部分):
def find_keys(dct):
for k, v in dct.items():
if isinstance(v, dict):
yield from (f"{k}->{x}" for x in find_keys(v))
else:
yield k
dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}
print(*find_keys(dct)) # A->AA A->BB->BBB A->BB->CCC
如果您想改用 return
,则:
def find_keys(dct):
result = []
for k, v in dct.items():
if isinstance(v, dict):
result += [f"{k}->{x}" for x in find_keys(v)]
else:
result.append(k)
return result
我有一个嵌套字典,如下所示:
dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}
我想提取列表格式的所有键序列,直到达到最深的 key:value 对。
预期的输出是这样的:
["A->AA", "A->BB->BBB", "A->BB->CCC"]
我尝试的解决方案是:
for k, v in dct.items():
if isinstance(v, dict):
# traverse nested dict
for x in find_keys(v):
yield "{}_{}".format(k, x)
print("{}_{}".format(k, x))
else:
yield k
print(k)
但它似乎没有按预期工作。
我猜你已经差不多了(或错误地省略了一些部分):
def find_keys(dct):
for k, v in dct.items():
if isinstance(v, dict):
yield from (f"{k}->{x}" for x in find_keys(v))
else:
yield k
dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}
print(*find_keys(dct)) # A->AA A->BB->BBB A->BB->CCC
如果您想改用 return
,则:
def find_keys(dct):
result = []
for k, v in dct.items():
if isinstance(v, dict):
result += [f"{k}->{x}" for x in find_keys(v)]
else:
result.append(k)
return result