问题描述
我在理解Python 3中的嵌套字典理解时遇到麻烦.我从下面的示例中得到的结果输出的是正确的结构,没有错误,但只包含一个内部键:值对.我还没有找到像这样的嵌套字典理解的例子.谷歌搜索嵌套词典理解python"显示了遗留示例,非嵌套理解或使用其他方法解决的答案.我可能使用了错误的语法.
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.
示例:
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()}
此示例应返回原始字典,但内部值由myfunc
修改.
This example should return the original dictionary, but with the inner value modified by myfunc
.
outer_dict字典的结构以及结果:
Structure of the outer_dict dictionary, as well as the result:
{outer_k: {inner_k: inner_v, ...}, ...}
推荐答案
{inner_k: myfunc(inner_v)}
不是字典理解.只是字典而已.
{inner_k: myfunc(inner_v)}
isn't a dictionary comprehension. It's just a dictionary.
您可能正在寻找类似这样的东西:
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.
这篇关于嵌套字典理解python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!