So I have the following simple function that converts a dictionary to a list
of tuple
s. 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.
JavaScript
x
11
11
1
import typing as t
2
3
def _dict_to_map(dict_: t.Dict[t.Any, t.Union[t.Dict, t.Any]]):
4
map_ = []
5
for k, v in dict_.items():
6
if isinstance(v, dict):
7
map_.append((k, _dict_to_map(v)))
8
else:
9
map_.append((k, v))
10
return map_
11
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:
JavaScript
1
5
1
def _dict_to_map(d):
2
if not isinstance(d, dict):
3
return d
4
return [(k, _dict_to_map(v)) for k, v in d.items()]
5