Python – How (or is it possible) to use lists to extract nested dictionaries in Python?

How (or is it possible) to use lists to extract nested dictionaries in Python?… here is a solution to the problem.

How (or is it possible) to use lists to extract nested dictionaries in Python?

I have such a dictionary in Python:

d = {
    "k1": "v1",
    "k2": {
        "nk1": "v2"
    },
    "k3": "v3"
}

I

have a list of the keys I want to fetch, some of which are nested keys :

extract = ["k1", "nk1", "k3"]

Or I can define it this way to show that nk1 is nested in k2, I don’t need the value of “k2” because it’s just a nested dictionary:

extract = ["k1", ["k2", "nk1"], "k3"]

Is there a way to

iterate through this extract list and get all the values I need, or is there an easier way to check if a key is present in a nested dictionary?

The ideal output is a dictionary:

r = {
    "k1": "v1",
    "nk1": "v2",
    "k3": "v3"
}

Solution

You can use functools.reduce to get the value specified for a given list of keys:

from functools import reduce
dict((k[-1], reduce(dict.get, k, d)) if isinstance(k, list) else (k, d[k]) for k in extract)

Given your example input, this will return:

{'k1': 'v1', 'nk1': 'v2', 'k3': 'v3'}

Related Problems and Solutions