【问题标题】:How to convert the keys of Python dictionary to string for all nested dictionaries too如何将 Python 字典的键也转换为所有嵌套字典的字符串
【发布时间】:2023-01-07 00:25:48
【问题描述】:
我有一本字典:
d = {
"A": {
dt.date(2022, 5, 31): "AA"
},
dt.date(2022, 12, 12): "BB"
}
我想将所有 datetime.date 键转换为所有嵌套词典的字符串。
结果应该是:
d = {
"A": {
"2022/05/31": "AA"
},
"2022/12/12": "BB"
}
我怎样才能做到这一点?
【问题讨论】:
标签:
python
python-3.x
dictionary
【解决方案1】:
您可以使用递归函数来处理任意嵌套:
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)
输出:
{'A': {'2022/05/31': 'AA'}, '2022/12/12': 'BB'}