繁体   English   中英

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

[英]Best practice for updating list of dicts in Python

想知道是否存在“最佳实践”方法来更新dicts list的项目。

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

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

我知道我可以在带有rangeenumeratefor循环中进行更新

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有很多键/值对,这种方法可能会容易出错。

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

附言:我注意到循环比理解速度要快得多。 这会影响事物吗?

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

列表理解创建新的dict而不是更新现有的dict,因此速度较慢。
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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM