Nested dictionary comprehension 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.

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.

Structure of the outer_dict dictionary, as well as the result:

{outer_k: {inner_k: inner_v, ...}, ...}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x