Home > Software engineering >  python find and replace all values under a certain key in a nested dictionary
python find and replace all values under a certain key in a nested dictionary

Time:03-20

Given any supplied key and value, I want to replace every value under that key no matter where it is in the dictionary

Example:

input -> key='a', value='HELLO', 
{
  'a': [1],
  'b': {
    'c': 1,
    'a': {
      'd': 'string',
      'e': [1, 2]
    },
    'f': [1, 3]
  }
}

output ->
{
  'a': 'HELLO',
  'b': {
    'c': 1,
    'a': 'HELLO',
    'f': [1, 3]
  },
}

CodePudding user response:

You can use recursion. You'll need to supply logic for diving into each container type you care about supporting. As an example, this is how you could handle values in nested dicts or lists.

def replace_nested_key(data, key, value):
    if isinstance(data, dict):
        return {
            k: value if k == key else replace_nested_key(v, key, value)
            for k, v in data.items()
        }
    elif isinstance(data, list):
        return [replace_nested_key(v, key, value) for v in data]
    else:
        return data

CodePudding user response:

You can loop through every key and value pair in the array until you get the specified name, and set the value to it.

def find_and_replace_values_in_nested_dictionary(dictionary, key, value):
    if isinstance(dictionary, dict):
        for k, v in dictionary.items():
            if k == key:
                dictionary[k] = value
            else:
                if isinstance(v, dict):
                    solution(v, key, value)
                elif isinstance(v, list):
                    for i in v:
                        if isinstance(i, dict):
                            solution(i, key, value)
    return dictionary

dictionary = {
    'a': [1],
    'b': {
        'c': 1,
        'a': {
            'd': 'string',
            'e': [1, 2]
        },
        'f': [1, 3]
    }
}
print(find_and_replace_values_in_nested_dictionary(dictionary, 'a', 'HELLO'))

CodePudding user response:

Use recursion to make things easy.

Instead of modifying the original dictionary I am creating a copy of the dictionary and modifying it.

The method change recursively call itself.

import copy

a = {
  'a': [1],
  'b': {
    'c': 1,
    'a': {
      'd': 'string',
      'e': [1, 2]
    },
    'f': [1, 3]
  }
}

def change(a:dict, key, value):
    n = copy.deepcopy(a)
    for k, v in a.items():
        if k == key:
            n[k] = value
        elif isinstance(v, dict) :
            n[k] = change(v, key, value)
    return n


print(change(a=a,key='a',value='HELLO')) 

Output:

{'a': 'HELLO', 'b': {'c': 1, 'a': 'HELLO', 'f': [1, 3]}}

ps : Thanks Flakes for isinstance suggestion to identify the dictionary type.

  • Related