【问题标题】:Recursively replace characters in a python3 dictionary递归替换python3字典中的字符
【发布时间】:2020-11-05 16:23:28
【问题描述】:

我已经看到很多关于递归替换字典中特定字符的答案。但那些是字典中的字典。

我正在寻找一种解决方案来递归替换 python 字典的所有值中的某些字符或单词,但字典值可以是字符串、int、dict 或数组。例如,

pydict = {
  'type': 'identity1',
  'desc': ['tan', 'grey', 'blue_brown'],
  'location': {
    'warehouse': "area '1'",
    'warehouse2': 'area 2'
  },
  'quant': 2
}

replacement_dict = {'tan': 'orange', "'": '"', '2': '3'}

所以我想用replacement_dict值替换pydict值中replacement_dict键中匹配的每个单词或字符。

【问题讨论】:

  • 如果您添加了预期的结果,我会很好,特别是因为您的数据中有 '2'2,替换值中有 '3'。你预计quant会发生什么吗?
  • 试着展示你到目前为止所做的事情
  • 有趣。谷歌同样的问题,但使用“json”而不是 Python。同时我会尝试一些事情......

标签: python dictionary recursion


【解决方案1】:

这很简单,你首先处理所有想要加深递归的情况,即列表和字典,然后应用替换。我假设所有的实际数据都是字符串类型,但我相信你可以处理更多的情况(我只是不想把它们打出来)。代码如下。

pydict = {'type': 'identity1', 'desc': ['tan', 'grey', 'blue_brown'], 'location': {'warehouse': "area '1'", 'warehouse2': 'area 2'}, 'quant': 2}

replacement_dict = {'tan': 'orange', "'": '"', '2': '3'}

def replace_rec(d):
    if type(d)==list:
        d = [replace_rec(x) for x in d]
    elif type(d)==dict: 
        for k in d.keys():  
            d[k] = replace_rec(d[k])
    else:
        for k, v in replacement_dict.items():   
           d = str(d).replace(k,v)
    return d

r = replace_rec(pydict)
print(pydict)
print(r)

【讨论】: