递归地遍历带有列表的嵌套字典,并替换匹配的值 [英] Recursively iterate through a nested dict with list, and replace matched values

查看:139
本文介绍了递归地遍历带有列表的嵌套字典,并替换匹配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个通过包含列表的嵌套字典迭代的函数。对于每个与关键字匹配的值,该函数将其替换为另一个关键字。



该函数返回另一个dict或更改主dict并不重要。 / p>

我试图将情况分开:
-如果数据是字典,则进行某些操作
-如果数据是列表,则进行其他操作



DICT:

  
data_dict = {
name: AAAAAA,
content: BBBBBB,
dat:[
{
author :{{
name: CCCCCC,
surname: DDDDDD,
},
title: FFFFFF,
color :15258703,
字段:[
{
name: GGGGGG,
value: HHHHHH,
},
{
name: IIIIII,
value: JJJJJJ,
}

],
缩略图: {
url: KKKKKK
},
image:{
url: LLLLLL
},
footer:{
text: MMMMMMM,
icon_url : NNNNNN
}
}
]
}


现在我只是想更改每个值以查看是否也要进行迭代。
我可以打印所有更改后的 data_dict ,但是我无法在字典中对其进行管理...

  
def recursive_replace_valuer(data,match,repl):

如果isinstance(data,list) :数据中的l的

recursive_replace_valuer(l,match,repl)
if isinstance(l,dict):
recursive_replace_valuer(l,match,repl)




elif isinstance(data,dict):
for data中的k,v.items():
recursive_replace_valuer(v,match,repl )
data [k] ='______'
print(data)

recursive_replace_valuer(data_dict,'a','a')


解决方案

该函数应递归地将该函数应用于字典或列表中的值,直到输入 data 既不是字典也不是列表,这时如果替换值 repl ,则返回替换值给定的数据与给定的搜索字符串 match

  def replace(数据,匹配项,替换项):
如果isinstance(数据,字典):
返回{k:data.items()中k,v的replace(v,match,repl)}
elif isinstance(data,list):
返回[在数据中为i替换(i,match,repl)]
else:
如果data ==匹配else data
返回repl

或者就地替换原始数据,使函数遍历给定的dict或list并替换为键(用于dict)或索引(用于列表)(如果匹配),然后将该函数递归应用到值:

  def replace(数据,匹配,替换):
如果isinstance(数据,(字典,列表)):
对于k,v in(data.items()如果isinstance(数据,字典)否则枚举(数据)):如果v ==匹配,则为

data [k] = repl
replace(v,match,repl)


I want to make a function that iterate through a nested dict that include list. For each value that match with a keyword, the function replace it with another keyword.

It's not important if the function return another dict or if it change the main dict.

I tried to separate the case: - if the data is a dict, make something - if the data is a list, make something else

DICT:


data_dict = {
  "name": "AAAAAA",
  "content": "BBBBBB",
  "dat": [
    {
      "author": {
        "name": "CCCCCC",
        "surname": "DDDDDD",
      },
      "title": "FFFFFF",
      "color": 15258703,
      "fields": [
        {
          "name": "GGGGGG",
          "value": "HHHHHH",
        },
        {
          "name": "IIIIII",
          "value": "JJJJJJ",
        }

      ],
      "thumbnail": {
        "url": "KKKKKK"
      },
      "image": {
        "url": "LLLLLL"
      },
      "footer": {
        "text": "MMMMMMM",
        "icon_url": "NNNNNN"
      }
    }
  ]
}


Now I'm just trying to change each value to see if I'm iterate as well. I can print all the data_dict with value changed, but I can't manage it in a dict...


def recursive_replace_valuer(data, match, repl):

    if isinstance(data, list):
        for l in data:
            recursive_replace_valuer(l, match, repl)
            if isinstance(l, dict):
                recursive_replace_valuer(l, match, repl)




    elif isinstance(data, dict):
        for k,v in data.items():
            recursive_replace_valuer(v, match, repl)
            data[k] = '______'
        print(data)

recursive_replace_valuer(data_dict, 'a','a')

解决方案

The function should recursively apply the function to the values in a dict or a list until the input data is neither a dict nor a list, at which point return the replacement value repl if the given data matches the given search string match:

def replace(data, match, repl):
    if isinstance(data, dict):
        return {k: replace(v, match, repl) for k, v in data.items()}
    elif isinstance(data, list):
        return [replace(i, match, repl) for i in data]
    else:
        return repl if data == match else data

Or to replace the original data in-place, make the function iterate through the given dict or list and replace a value by the key (for dict) or index (for list) if it's a match, and recursively apply the function to the value:

def replace(data, match, repl):
    if isinstance(data, (dict, list)):
        for k, v in (data.items() if isinstance(data, dict) else enumerate(data)):
            if v == match:
                data[k] = repl
            replace(v, match, repl)

这篇关于递归地遍历带有列表的嵌套字典,并替换匹配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆