嵌套字典理解python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17915117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested dictionary comprehension python
提问by Turtles Are Cute
I'm having trouble understanding nested dictionary comprehensions in Python 3. The result I'm getting from the example below outputs the correct structure without error, but only includes one of the inner key: value pairs. I haven't found an example of a nested dictionary comprehension like this; Googling "nested dictionary comprehension python" shows legacy examples, non-nested comprehensions, or answers solved using a different approach. I may be using the wrong syntax.
我在理解 Python 3 中的嵌套字典推导式时遇到了麻烦。我从下面的示例中得到的结果输出了正确的结构,没有错误,但只包含一个内部键:值对。我还没有找到这样的嵌套字典理解的例子;谷歌搜索“嵌套字典理解 python”显示遗留示例、非嵌套理解或使用不同方法解决的答案。我可能使用了错误的语法。
Example:
例子:
data = {outer_k: {inner_k: myfunc(inner_v)} for outer_k, outer_v in outer_dict.items() for inner_k, inner_v in outer_v.items()}
This example should return the original dictionary, but with the inner value modified by myfunc
.
此示例应返回原始字典,但内部值由myfunc
.
Structure of the outer_dict dictionary, as well as the result:
outer_dict 字典的结构,以及结果:
{outer_k: {inner_k: inner_v, ...}, ...}
采纳答案by Blender
{inner_k: myfunc(inner_v)}
isn't a dictionary comprehension. It's just a dictionary.
{inner_k: myfunc(inner_v)}
不是字典理解。这只是一本字典。
You're probably looking for something like this instead:
你可能正在寻找这样的东西:
data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}
For the sake of readability, don't nest dictionary comprehensions and list comprehensions too much.
为了可读性,不要过多地嵌套字典推导和列表推导。
回答by Zero Piraeus
Adding some line-breaks and indentation:
添加一些换行符和缩进:
data = {
outer_k: {inner_k: myfunc(inner_v)}
for outer_k, outer_v in outer_dict.items()
for inner_k, inner_v in outer_v.items()
}
... makes it obvious that you actually have a single, "2-dimensional" dict comprehension. What you actually want is probably:
... 很明显你实际上有一个单一的“二维”字典理解。你真正想要的可能是:
data = {
outer_k: {
inner_k: myfunc(inner_v)
for inner_k, inner_v in outer_v.items()
}
for outer_k, outer_v in outer_dict.items()
}
(which is exactly what Blender suggested in his answer, with added whitespace).
(这正是 Blender 在他的回答中建议的,并添加了空格)。
回答by Gajendra D Ambi
{ok: {ik: myfunc(iv) for ik, iv in ov.items()} for ok, ov in od.items()}
where
ok-outer key
ik-inner key
ov-outer value
iv-inner value
od-outer dictionary
This is how i remember.
where
ok-outer key
ik-inner key
ov-outer value
iv-inner value od-outer dictionary 这是我记得的。