Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, ...}, ...} 
like image 925
Turtles Are Cute Avatar asked Jul 29 '13 02:07

Turtles Are Cute


People also ask

Can you do dictionary comprehension in Python?

Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions.

Is dictionary comprehension faster than for loop?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

Why do we use dictionary comprehension in Python?

Dictionaries in Python allow us to store a series of mappings between two sets of values, namely, the keys and the values. All items in the dictionary are enclosed within a pair of curly braces {} . Each item in a dictionary is a mapping between a key and a value - called a key-value pair.


2 Answers

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

like image 50
Blender Avatar answered Sep 20 '22 15:09

Blender


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

like image 28
Zero Piraeus Avatar answered Sep 17 '22 15:09

Zero Piraeus