简体   繁体   English

Python - 迭代和更新嵌套字典和列表

[英]Python - iterate and update a nested dictionary & lists

Having the following dict, where some of the values can be list of dictionaries:有以下字典,其中一些值可以是字典列表:

{
  "A": [
    {
      "B": {
        "C": "D",
        "X": "CHNAGE ME"
      }
    },
    {
      "E": "F"
    }
  ],
  "G": {
    "Y": "CHANGE ME"
  }
}

I would like to recursively iterate over the items and change the pairs of key values where the value is "CHANGE ME", so the result would be:我想递归迭代这些项目并更改值为“CHANGE ME”的键值对,因此结果将是:

{
  "A": [
    {
      "B": {
        "C": "D",
        "X.CHANGED": "CHANGED"
      }
    },
    {
      "E": "F"
    }
  ],
  "G": {
    "Y.CHANGED": "CHANGED"
  }
}

Solutions I've found were not handling a case where the value is a list, for example:我发现的解决方案没有处理值是列表的情况,例如:

import collections
def nested_dict_iter(nested):
    for key, value in nested.iteritems():
        if isinstance(value, collections.Mapping):
            for inner_key, inner_value in nested_dict_iter(value):
                yield inner_key, inner_value
        else:
            yield key, value

How can I achieve my goal?我怎样才能实现我的目标?

Using recursion使用递归

Ex:前任:

def update(data):
    for k, v in data.copy().items():
        if isinstance(v, dict):     # For DICT
            data[k] = update(v)
        elif isinstance(v, list):   # For LIST
            data[k] = [update(i) for i in v]
        elif v == 'CHANGE ME':      # Update Key-Value
            # data.pop(k)
            # OR
            del data[k]
            data[f"{k}.CHANGED"] = 'CHANGED'
    
    return data

print(update(data))

Output:输出:

{
    'A':[{'B': {'C': 'D', 'X.CHANGED': 'CHANGED'}}, {'E': 'F'}], 
    'G':{'Y.CHANGED': 'CHANGED'}
 }

Note : I have not tested all corner cases注意:我没有测试所有的极端情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM