Python:替换嵌套字典中的值

Jon*_*Fly 5 python iteration dictionary

每当键为“ current_values ”时,我想用与“ integers ”相同的值替换值(格式为字符串)。

d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
Run Code Online (Sandbox Code Playgroud)

期望的输出:

d = {'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
Run Code Online (Sandbox Code Playgroud)

Neb*_*tic 22

以下代码段替换字典中的值(的子字符串)。它适用于嵌套 json 结构并处理 json、列表和字符串类型。如果需要,您可以轻松添加其他类型。

def dict_replace_value(d: dict, old: str, new: str) -> dict:
    x = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = dict_replace_value(v, old, new)
        elif isinstance(v, list):
            v = list_replace_value(v, old, new)
        elif isinstance(v, str):
            v = v.replace(old, new)
        x[k] = v
    return x


def list_replace_value(l: list, old: str, new: str) -> list:
    x = []
    for e in l:
        if isinstance(e, list):
            e = list_replace_value(e, old, new)
        elif isinstance(e, dict):
            e = dict_replace_value(e, old, new)
        elif isinstance(e, str):
            e = e.replace(old, new)
        x.append(e)
    return x

# See input and output below
output = dict_replace_value(input, 'string', 'something')
Run Code Online (Sandbox Code Playgroud)

输入:

input = {
    'key1': 'a string',
    'key2': 'another string',
    'key3': [
        'a string',
        'another string',
        [1, 2, 3],
        {
            'key1': 'a string',
            'key2': 'another string'
        }
    ],
    'key4': {
        'key1': 'a string',
        'key2': 'another string',
        'key3': [
            'a string',
            'another string',
            500,
            1000
        ]
    },
    'key5': {
        'key1': [
            {
                'key1': 'a string'
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

print(output)

{
   "key1":"a something",
   "key2":"another something",
   "key3":[
      "a something",
      "another something",
      [
         1,
         2,
         3
      ],
      {
         "key1":"a something",
         "key2":"another something"
      }
   ],
   "key4":{
      "key1":"a something",
      "key2":"another something",
      "key3":[
         "a something",
         "another something",
         500,
         1000
      ]
   },
   "key5":{
      "key1":[
         {
            "key1":"a something"
         }
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 我遇到了同样的问题,大多数答案都没有比一级嵌套结构更进一步。所以这就是我提出上述答案的原因。 (2认同)

Dir*_*Bit 4

d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}

for elem in d['datastreams']:      # for each elem in the list datastreams
    for k,v in elem.items():       # for key,val in the elem of the list 
        if 'current_value' in k:   # if current_value is in the key
            elem[k] = int(v)       # Cast it to int
print(d)
Run Code Online (Sandbox Code Playgroud)

输出

{'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
Run Code Online (Sandbox Code Playgroud)