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

Time:01-07

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?

CodePudding user response:

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'}
  • Related