在 Python 中创建新的字典键时,使用"update"而不是简单地 = 创建它有什么好处吗?



假设我正在创建一个不包含任何子键的键值对。

self.profiles[server.id][author.id]['games']['accounts']['league']已经存在。使用是否有任何好处或目的

self.profiles[server.id][author.id]['games']['accounts']['league'].update({'plays': true})

self.profiles[server.id][author.id]['games']['accounts']['league']['plays'] = True

使用仅更改一个键的.update效率会大大降低。

桌面上的简单基准测试

$ python -m timeit -s 'd={}' 'd.update({"x":3})'
1000000 loops, best of 3: 0.263 usec per loop
$ python -m timeit -s 'd={}' 'd["x"]=3'
10000000 loops, best of 3: 0.0409 usec per loop

这是因为要使用.update更新键,它需要创建一个新字典,然后遍历字典中的所有密钥(即使只有一个(。另外,在 Python 中函数调用总是有开销。

在您的情况下,最好使用 set 项语法。

但是,如果您想将多个对添加到字典中,这就是更新的亮点:

d = {'a':1, 'b':2}
new_pairs = {'c':3, 'd':4}
d.update(new_pairs)  
print(d)   # d = {'a':1, 'b':2, 'c':3, 'd':4}

这还将更改同时处于dnew_pairs中的键的值(值为new_pairs[k](:

d = {'a':1, 'b':"before"}
new_pairs = {'b':"after", 'c':3, 'd':4}
d.update(new_pairs)
print(d)  # {'a': 1, 'b': 'after', 'c': 3, 'd': 4}

最新更新