我在用一个dict。它有一些嵌套的dict。看起来是这样的:
如您所见,education
和experience
有嵌套的dict。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])
换句话说,继续索引嵌套的dict(如果存在的话),直到找到一个字符串值。你知道吗
更好的答案可能适用于一般情况:嵌套在其他dict中的dict数量可变。也许嵌套的dict有好几层深(dict在dict中dict在dict中dict在dict中…直到最后碰到一些字符串/整数)。你知道吗
可以使用递归函数。你知道吗
此函数将遍历字典,当它遇到一个列表时,它将遍历该列表中的每个字典,直到找到您要查找的键为止。然后将该条目的值更改为新的\u文本:
根据您的注释,如果要更改每个字符串,而不考虑键(不包括键本身):
在这里,您可以为dict添加一些结构,因为主dict中每个键的值可以是dict列表、字符串或字符串列表,所以您必须考虑许多输入情况。我不确定您是否已经了解了典型的tree data structures,但是在这里创建一个node类并确保每个部分都是一个节点会有所帮助。你知道吗
相关问题 更多 >
编程相关推荐