[Solved] Replace items in a dict of nested list and dicts


A recursive function that creates a new nested dictionary, replacing a key value with a different value

def replace_key(elem, old_key, new_key):
    if isinstance(elem, dict):
        # nested dictionary
        new_dic = {}
        for k, v in elem.items():
            if isinstance(v,dict) or isinstance(v, list):
                new_dic[replace_key(k, old_key, new_key)] = replace_key(v, old_key, new_key)
            else:
                new_dic[replace_key(k, old_key, new_key)] = v

        return new_dic

    elif isinstance(elem, list):
        # nested list
        return [replace_key(t, old_key, new_key) for t in elem]

    else:
        return elem


di = {"a": "A", "b": "B", "c": [2, 4, 6, {"a": "A", "b": "B"}], "d": {"a": [2, 4, 6], "b": [5, 2, 1]}}

print(replace_key(di, 'a', 'z'))

Output

{'z': 'A', 'c': [2, 4, 6, {'z': 'A', 'b': 'B'}], 'd': {'z': [2, 4, 6], 'b': [5, 2, 1]}, 'b': 'B'}

**Performance Comparison (using Jupyter Notebook) **

Result: ComplicatedPhenomenon post has the fastest time by 10X over other two methods.

1. Reznik Post–JSON load substitution

   %timeit json.loads(json.dumps(di).replace('a', 'z'))

23.6 µs ± 2.05 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

2. DarrylG–Recursive Function

%timeit replace_key(di, 'a', 'z')

20.1 µs ± 424 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

3. ComplicatedPhenomenon Post–specialized to particular structure

%%timeit
d = {"a": "A", "b": "B", "c": [2, 4, 6, {"a": "A", "b": "B"}], "d": {"a": [2, 4, 6], "b": [5, 2, 1]}}
d['z'] = d.pop('a')           
d['d']['z'] = d['d'].pop('a')      
d['c'][3]['z'] = d['c'][3].pop('a') 

2.03 µs ± 211 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

3

solved Replace items in a dict of nested list and dicts