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

Question:

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:

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

How can I do that?

Asked By: Merger

||

Answers:

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'}
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.