有没有办法在找到字符串值之前一直为嵌套词典编制索引?

2024-09-28 15:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用一个dict。它有一些嵌套的dict。看起来是这样的:

如您所见,educationexperience有嵌套的dict。skillsindustrysummary只是带有值的键。你知道吗

{
  "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"
}

我需要访问与键startmajor、来自skillsindustryorgdescsummary的字符串列表对应的所有值,以便修改字符串。你知道吗

有没有什么方法可以访问这样的值:

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中…直到最后碰到一些字符串/整数)。你知道吗


Tags: 字符串textorgkeyssummarystartdescdict
1条回答
网友
1楼 · 发布于 2024-09-28 15:29:54

可以使用递归函数。你知道吗

此函数将遍历字典,当它遇到一个列表时,它将遍历该列表中的每个字典,直到找到您要查找的键为止。然后将该条目的值更改为新的\u文本:

    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

在这里,您可以为dict添加一些结构,因为主dict中每个键的值可以是dict列表、字符串或字符串列表,所以您必须考虑许多输入情况。我不确定您是否已经了解了典型的tree data structures,但是在这里创建一个node类并确保每个部分都是一个节点会有所帮助。你知道吗

相关问题 更多 >