在Python中更新字典列表的最佳实践

时间:2018-09-06 03:48:31

标签: python python-3.x list dictionary

想知道是否有“最佳实践”方法来更新listdicts中的项目。

假设我有以下内容,我想为列表中的每个字典更新key1

data = [
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
]

我知道我可以使用forrange这样的enumerate循环进行更新

for i, d in enumerate(data):
    data[i]['key1'] = 'value4'

我也可以使用list理解力

data = [{'key1': 'value4', 'key2': d['key2'], 'key3': d['key3']} for d in data]

但是,如果dict中有很多键/值对,我觉得这种方法可能容易出错,

还有其他我忽略的方法吗?

PS我注意到循环明显比理解速度要快。这会发挥作用吗?

In [12]: %timeit [{'key1': 'value4', 'key2': d['key2'], 'key3': d['key3']} for d in data]
The slowest run took 8.41 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.25 µs per loop

In [14]: %timeit for i, d in enumerate(data): data[i]['key1'] = 'value4'
The slowest run took 5.20 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 541 ns per loop

1 个答案:

答案 0 :(得分:0)

列表理解会创建新字典而不是更新现有字典,因此速度较慢。
update_2()可能更快:

data = [
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
]

def update_1():
    for i, d in enumerate(data):
        data[i]['key1'] = 'value4'

def update_2():
    for d in data:
        d['key1'] = 'value4'

for _ in range(100000):
    update_1()

for _ in range(100000):
    update_2()

然后python -m cProfile test.py

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   100000    0.039    0.000    0.039    0.000 t.py:12(update_2)
        1    0.059    0.059    0.188    0.188 t.py:2(<module>)
   100000    0.090    0.000    0.090    0.000 t.py:8(update_1)
        1    0.000    0.000    0.188    0.188 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}