Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert the keys of Python dictionary to string for all nested dictionaries too

I have a dictionary:

d = {
    "A": {
        dt.date(2022, 5, 31): "AA"
    },
    dt.date(2022, 12, 12): "BB"
}

and I want to convert all the datetime.date keys to strings for all the nested dictionaries.

The results should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

d = {
    "A": {
        "2022/05/31": "AA"
    },
    "2022/12/12": "BB"
}

How can I do that?

>Solution :

You can use a recursive function to handle an arbitrary nesting:

import datetime as dt

def dt_to_str(d):
    return {k.strftime('%Y/%m/%d') if isinstance(k, dt.date) else k:
            dt_to_str(v) if isinstance(v, dict) else v
            for k, v in d.items()}

out = to_str(d)

Output:

{'A': {'2022/05/31': 'AA'}, '2022/12/12': 'BB'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading