Using dictionary comprehension is it possible to convert all values recursively to string?
I have this dictionary
JavaScript
x
9
1
d = {
2
"root": {
3
"a": "1",
4
"b": 2,
5
"c": 3,
6
"d": 4
7
}
8
}
9
I tried
JavaScript
1
2
1
{k: str(v) for k, v in d.items()}
2
But the code above turns the entire root
value into string and I want this:
JavaScript
1
2
1
d = {"root": {"a": "1", "b": "2", "c": "3", "d": "4"}}
2
Advertisement
Answer
This is not a dictionary comprehension, but it works, it’s just one line, and it’s recursive!
JavaScript
1
2
1
(f := lambda d: {k: f(v) for k, v in d.items()} if type(d) == dict else str(d))(d)
2
It only works with Python 3.8+ though (because of the use of an assignment expression).