Skip to content
Advertisement

Recursive convert values to string using dictionary comprehension

Using dictionary comprehension is it possible to convert all values recursively to string?

I have this dictionary

d = {
  "root": {
    "a": "1",
    "b": 2,
    "c": 3,
    "d": 4
  }
}

I tried

{k: str(v) for k, v in d.items()}

But the code above turns the entire root value into string and I want this:

d = {"root": {"a": "1", "b": "2", "c": "3", "d": "4"}}

Advertisement

Answer

This is not a dictionary comprehension, but it works, it’s just one line, and it’s recursive!

(f := lambda d: {k: f(v) for k, v in d.items()} if type(d) == dict else str(d))(d)

It only works with Python 3.8+ though (because of the use of an assignment expression).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement