'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_
Solution 1:[1]
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()]
Solution 2:[2]
Yes you can
def _dict_to_map(dict_: t.Dict[t.Any, t.Union[t.Dict, t.Any]]):
return [(k, _dict_to_map(v)) if isinstance(v, dict) else (k, v)
for k, v in dict_.items()]
Solution 3:[3]
Sure. When you populate a list with append in a for loop, you can turn it into list comprehension, just by moving parts:
return [(k, _dict_to_map(v) if isinstance(v, dict) else v)
for k, v in dict_.items()]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
| Solution 2 | azro |
| Solution 3 | trincot |
