我正在处理字典。它有一些嵌套的字典。看起来像这样:
如您所见,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
,{{ 1}}和desc
,以便我可以修改字符串。
那么有某种方法可以访问像这样的值:
summary
换句话说,继续为嵌套的dict(如果存在)建立索引,直到找到字符串值。
一个更好的答案可能是处理一般情况:嵌套在其他字典中的可变数目的字典。也许有嵌套的dict深入了几层(在dict里面的dict里面的dict里面的dict ...直到最终您击中了一些字符串/整数)。
答案 0 :(得分:2)
您可以使用递归函数。
此函数将遍历字典,当遇到列表时,它将遍历该列表中的每个字典,直到找到您要查找的键。然后将该项的值更改为new_text:
def change_all_key_text(input_dict, targ_key, new_text):
for key, val in input_dict.items():
if key == targ_key:
input_dict[key] = new_text
elif isinstance(val, list):
for new_dict in val:
if isinstance(new_dict, dict):
change_all_key_text(new_dict, targ_key, new_text)
根据您的评论,如果您想更改每个字符串,而不论键(键本身除外):
def modify_all_strings(input_iterable, new_text):
if isinstance(input_iterable, dict):
for key, val in input_iterable.items():
if isinstance(val, dict) or isinstance(val, list):
modify_all_strings(val, new_text)
else:
# make changes to string here
input_iterable[key] = new_text
elif isinstance(input_iterable, list):
for idx, item in enumerate(input_iterable):
if isinstance(item, dict) or isinstance(item, list):
modify_all_strings(item, new_text)
else:
# make changes to string here
input_iterable[idx] = new_text
在这里,您将为字典增加一些结构将会受益。由于主字典中每个键的值可以是字典列表,字符串或字符串列表,因此必须考虑许多输入情况。我不确定您是否已经了解典型的tree data structures,但可以帮助您创建节点类并确保每个部分都是一个节点。