Skip to content
Advertisement

Recursive Function to List Comprehension

So I have the following simple function that converts a dictionary to a list of tuples. I was curious if there is a way to do this with list comprehension. I know this would not be good form code-wise, but I would like to just understand if it is possible if we do not know the depth.

import typing as t

def _dict_to_map(dict_: t.Dict[t.Any, t.Union[t.Dict, t.Any]]):
    map_ = []
    for k, v in dict_.items():
        if isinstance(v, dict):
            map_.append((k, _dict_to_map(v)))
        else:
            map_.append((k, v))
    return map_

Advertisement

Answer

You can simplify the loop by moving your base case out of it, which in turn makes it easier to see how to turn it into a comprehension:

def _dict_to_map(d):
    if not isinstance(d, dict):
        return d
    return [(k, _dict_to_map(v)) for k, v in d.items()]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement