Skip to content

Nested dictionary comprehension Python

Don’t do Python Nested dictionary comprehension for the sake of readability, don’t nest dictionary comprehensions and list comprehensions too much. Comprehension is good for simple one-line code and is easy to read.

Structure Nested dictionary comprehension Python.

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()}

Nested dictionary comprehension Python

Simple example code 2 level nested dictionary comprehension.

data = [
    {
        'id': 1,
        'parent_id': 101,
        'name': 'A'
    },
    {
        'id': 2,
        'parent_id': 101,
        'name': 'B'
    },
    {
        'id': 3,
        'parent_id': 102,
        'name': 'C'
    },
    {
        'id': 4,
        'parent_id': 102,
        'name': 'D'
    }
]
data = {parent_id: {d["name"]: d["id"] for d in [i for i in data if i["parent_id"] == parent_id]} for parent_id in
        set((j["parent_id"] for j in data))}

print(data)

Output:

Nested dictionary comprehension Python

Python nested dict comprehension with if else

{fk: None
 for k, v in my_dict.items()
 for fk in ([k] if v is None else (k + fv for fv in v))}
  • If the value is None, you just want the key.
  • If the value is not None, you want a list of each value concatenated with the key.
  • Homogenize that to always returning a list, either of one key or multiple:
[k] if v is None else [k + fv for fv in v]

Then you’re looking at a “simple” nested comprehension:

{k: None for k in [['a'], ['b'], ['c1', 'c2', 'c3']] for fk in k}

Do comment if you have any doubts or suggestions on this Python comprehension topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

2 thoughts on “Nested dictionary comprehension Python”

  1. Hi Rohit

    Hope you are well. Found this post really interesting, I am new to python but I cannot make work the dictionary comprehension, any help will be greatly appreciated.

    I have a CSV that includes Name, Email, Year, Month, Day

    I am looking to end up with
    {(Month, Day): {Name: data_row (includes Year, Email)}

    birth_dict = {(data_row[“month”], data_row[“day”]): {d[“name”]:data_row for d in
    [i for i in data if i[“(data_row[“month”], data_row[“day”]”) == (data_row[“month”],
    data_row[“day”])] for j in data.iterrows()}

    I am doing a birthday wisher, what I want in my program is that when today is equal to Key (month, day). For every key seach for a name and send a message. I thought the best way was to create a nested diccionary where I could search the key (month, day) and then name.

    Let me know your thoughts, thanks in advance.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.