4

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"}}
3
  • 4
    I hope you know, "root": { "a", "1", "b", 2, "c", 3, "d", 4, }root's value is not a dictionary.=] Commented May 27, 2021 at 14:43
  • The question doesn't make sense if it's not a dictionary, since sets are not ordered Commented May 27, 2021 at 14:44
  • You right. Just fixed the question Commented May 27, 2021 at 14:45

5 Answers 5

7

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).

Sign up to request clarification or add additional context in comments.

Comments

2

You could do a recursive solution for arbitrarily nested dicts, but if you only have 2 levels the following is sufficient:

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

1 Comment

@Rodrigo You don't get this error if the inner dictionary is actually a dictionary
1

Assuming that your given input was wrong and root's value was a dictionary, your code would somewhat work. You just need to add d['root'].items()

newDict = {k:{k: str(v) for k, v in d[k].items()} for k,v in d.items()}

output

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

1 Comment

The key root was a example, could be anything
0

The following solution might not be using dictionary comprehension, but it is recursive and can transform dictionaries of any depth, I don't think that's possible using comprehension alone:

def convert_to_string(d):
    for key, value in d.items():
        if isinstance(value, dict):
            convert_to_string(value)
        else:
            d[key] = str(value)

Comments

0

Found a simpler way to to achieve this using json module. Just made the following

import json


string_json = json.dumps(d) # Convert to json string
d = json.loads(string_json, parse_int=str) # This convert the `int` to `str` recursively. 

Using a function

def dictionary_string(dictionary: dict) -> dict:
    return json.loads(json.dumps(dictionary), parse_int=str, parse_float=str)

Regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.