[英]dict of dicts python
I have a python dictionary consisting of other dictionaries like so (example): 我有一个由其他字典组成的python字典,例如(示例):
{2: {4: {5: {6: {7: None}}}, 7: None}, 7: None}
I would like to extract the keys so that I end up with: 我想提取密钥,以便最终得到:
[2,4,5,6,7,None]
[2,7,None]
[7,None]
I have tried to solve this problem with a recursive function, however with no luck... 我试图用递归函数解决这个问题,但是没有运气...
def f(d):
paths = []
try:
for key in f.keys():
path.append(f(d[key]))
pass:
pass
Is there a way to do this and how? 有办法做到吗?
The following seems to do the trick: 以下似乎可以解决问题:
def f(d):
paths = []
for key, value in d.items():
if value is None:
paths.append([key, value])
else:
internal_lists = f(value)
for l in internal_lists:
paths.append([key] + l)
return paths
1) Your try: loop is badly written: the syntax is 1)您的try:循环写得很烂:语法是
try:
xxx
except:
xxx
And do you expect a failure here? 您期望这里会失败吗? Why the try? 为什么要尝试?
2) Your loop can't be right neither: 2)您的循环也不正确:
for key in f.keys():
f is a function, it does not have keys. f是一个函数,它没有键。 d does. d做。
3) When dealing with a key, you need to keep it somewhere in the output, and you don't for the moment 3)处理键时,您需要将其保留在输出中的某个位置,并且暂时不需要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.