Nested dictionary comprehension python

丶灬走出姿态 提交于 2019-11-27 18:48:45

{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.

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).

{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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!