替换嵌套列表和字典中的项目

时间:2019-12-14 15:19:01

标签: python dictionary

有什么解决方案可以将dict的嵌套列表和python中的字典中的特定值替换为项目?

例如:

输入

item_to_be_replaced =  'a'

replaced_with = 'z'

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

输出

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

解决这个问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我不认为这是最好的选择,但是当我看到这个时,我想到了这个答案:

import json
json.loads(json.dumps(di).replace(f'"{item_to_be_replaced}"', f'"{replaced_with}"'))

简单地转换为字符串,替换我需要替换的东西,然后返回到dict

答案 1 :(得分:0)

一个递归函数,它创建一个新的嵌套字典,用另一个值替换键值

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'))

输出

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

**性能比较(使用Jupyter Notebook)**

结果:与其他两种方法相比,复杂现象发布的时间最快达到10倍。

1。 Reznik Post-JSON负载替换

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

每个循环23.6 µs±2.05 µs(平均±标准偏差,共运行7次,每个10000个循环)

2。 DarrylG-递归函数

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

每个循环20.1 µs±424 ns(平均±标准偏差,共运行7次,每个循环100000次)

3。复杂现象后-专门针对特定结构

%%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(平均±标准偏差,共运行7次,每个循环100000次)

相关问题