是否可以在 Python 字典创建后向其添加键?

它似乎没有 .add() 方法。

The conventional syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could also do:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See Dive Into Python, 5.6. Special Class Methods.

Let's pretend you want to live in the immutable world and do not want to modify the original but want to create a new dict that is the result of adding a new key to the original.

In Python 3.5+ you can do:

params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}

The Python 2 equivalent is:

params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})

After either of these:

params is still equal to {'a': 1, 'b': 2}


new_params is equal to {'a': 1, 'b': 2, 'c': 3}

There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3


params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})

Reference: What does `**` mean in the expression `dict(d1, **d2)`?

If you're not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.

import timeit

timeit.timeit(‘dictionary = {“karga”: 1, “darga”: 2}; dictionary.update({“aaa”: 123123, “asd”: 233})’)
>> 0.49582505226135254

timeit.timeit(‘dictionary = {“karga”: 1, “darga”: 2}; dictionary[“aaa”] = 123123; dictionary[“asd”] = 233;’)
>> 0.20782899856567383

However, if you'd like to add, for example, thousands of new key-value pairs, you should consider using the update() method.