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