【发布时间】:2019-11-13 15:40:42
【问题描述】:
我正在使用字典。它有一些嵌套的字典。它看起来像这样:
如您所见,education 和 experience 具有嵌套的字典。 skills、industry 和 summary 只是带有值的键。
{
"education": [
{
"start": "1991",
"major": "Human Resources"
},
{
"start": "1984",
"major": "Chemistry"
}
],
"skills": [
"AML",
"Relationship Management",
"Team Management"
],
"industry": "Banking",
"experience": [
{
"org": "Standard Chartered Bank",
"desc": "text"
},
{
"org": "Tesa Tapes India Pvt. Ltd.",
"desc": "text",
"start": "October 1993",
"title": "Product Manager/Application Engineer"
}
],
"summary": "text blah blah blah"
}
我需要访问与键start、major对应的所有值,以及来自skills、industry、org、desc和summary的字符串列表,这样我就可以修改字符串。
那么有没有办法像这样访问这些值:
for keys in outerDict.keys():
if outerDict[keys] has a nested dict:
for keys in nestedDict.keys():
nestedDict[keys] = doStuffToString(nestedDict[keys])
else:
outerDict[keys] = doStuffToString(outerDict[keys])
换句话说,继续索引嵌套的字典(如果它们存在的话),直到你找到一个字符串值。
一个更好的答案可能会处理一般情况:嵌套在其他字典中的可变数量的字典。也许有嵌套的 dicts 深入了几层(dicts inside of dicts inside of dicts inside of dicts...直到最终你遇到一些字符串/整数)。
【问题讨论】:
标签: python dictionary indexing