在嵌套词典上迭代仅返回第一个元素
我有这个嵌套词典(“字典词典”)
source = {
"OuterVal0": {"InnerVal": [10, 21, 96],"InnerVal2": [100, 91, 71]},
"OuterVal1": {"InnerVal": [21, 19, 76],"InnerVal2": [1, 1, 1]},
"OuterVal2": {"InnerVal": [1, 1, 96],"InnerVal2": [10, 9, 7]},
"OuterVal3": {"InnerVal": [0, 2, 6],"InnerVal2": [1, 911, 718]},
"OuterVal4": {"InnerVal": [12, 13, 9],"InnerVal2": [1000, 910, 701]},
"OuterVal5": {"InnerVal": [110, 211, 961],"InnerVal2": [10, 911, 918]},
}
,我想创建一个由与内部值相关的外键组成的新词语(请参见下面的预期输出) 我使用此递归功能:
def myPrint(d, key=""):
output = {}
for k, v in d.items():
i = 0
if isinstance(v, dict):
return myPrint(v, k)
else:
for value in d.values():
newkey = (f"{i}_{key}")
output[newkey] = value
i += 1
return output
但是当我尝试打印它时:
print(myPrint(source))
我得到了(只有第一个词典经过处理:
# {'0_OuterVal0': [10, 21, 96], '1_OuterVal0': [100, 91, 71]}
但是我想拥有这样的东西(所有词典已经处理过),
"""
Expected output
{'0_OuterVal0': [10, 21, 96], '1_OuterVal0': [100, 91, 71]}
{'0_OuterVal1':[21, 19, 76], '1_OuterVal1': [1, 1, 1]}
.
.
.
{'0_OuterVal5': [110, 211, 961], '1_OuterVal5': [10, 911, 918]}
"""
我在做什么错?
非常感谢您提前寻求帮助。
I have this nested dictionary ("dictionary of dictionaries")
source = {
"OuterVal0": {"InnerVal": [10, 21, 96],"InnerVal2": [100, 91, 71]},
"OuterVal1": {"InnerVal": [21, 19, 76],"InnerVal2": [1, 1, 1]},
"OuterVal2": {"InnerVal": [1, 1, 96],"InnerVal2": [10, 9, 7]},
"OuterVal3": {"InnerVal": [0, 2, 6],"InnerVal2": [1, 911, 718]},
"OuterVal4": {"InnerVal": [12, 13, 9],"InnerVal2": [1000, 910, 701]},
"OuterVal5": {"InnerVal": [110, 211, 961],"InnerVal2": [10, 911, 918]},
}
And I want to create a new one which would consist of outer keys associated with inner values (see expected output below)
I use this recursive function:
def myPrint(d, key=""):
output = {}
for k, v in d.items():
i = 0
if isinstance(v, dict):
return myPrint(v, k)
else:
for value in d.values():
newkey = (f"{i}_{key}")
output[newkey] = value
i += 1
return output
But when I try to print that:
print(myPrint(source))
I get this (only the first dictionary is processed:
# {'0_OuterVal0': [10, 21, 96], '1_OuterVal0': [100, 91, 71]}
But I would like to have something like this (all dictionaries processed)
"""
Expected output
{'0_OuterVal0': [10, 21, 96], '1_OuterVal0': [100, 91, 71]}
{'0_OuterVal1':[21, 19, 76], '1_OuterVal1': [1, 1, 1]}
.
.
.
{'0_OuterVal5': [110, 211, 961], '1_OuterVal5': [10, 911, 918]}
"""
What am I doing wrong?
Thank you very much in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题在于,当您调用
返回Myprint(v,k)
首次计算第一个字典的值,然后返回而不是继续返回for循环中的其他值。将函数更改为:
将返回一个大词典,例如:
但是,该函数可以以非收回的方式很好地包装,如以下方式:
The problem is that when you call
return myPrint(v, k)
for the first time you compute the values for the first dictionary and then return instead of continuing to the other values in the for loop.Changing the function to:
will return a big dictionary, for you example:
However, the function can be nicely packed in a non-recursive way as follow:
continue
Your desired output can be obtained more simply as a list comprehension:
This will create a list of dicts with the keys and values you specified.
使用调试器逐步执行代码会对您有所帮助:
当您调用 myPrint(source) 并进入 for 循环时,您确实递归地调用函数,但不是添加第一个嵌套字典到您的输出,您使用
return
关键字。因此,返回使用第一个键创建的字典,这就是函数的结束。如果您的函数的目的是打印,并且您想保留原始代码结构,您可以使用以下命令:
Following the execution of the code step by step with a debugger would help you :
When you call
myPrint(source)
and enter the for loop, you indeed call your function recursively, but instead of adding the 1st nested dictionary to your output, you use thereturn
keyword. so the dictionary created with the 1st key is returned and that's the end of your function.If the purpose of your function is to print, and that you want to keep your original code structure, you could use this :