3278

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

好像没有.add()方法。

4

23 回答 23

4156

您通过为该键分配一个值来在字典上创建一个新的键/值对

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

如果键不存在,则添加并指向该值。如果存在,则覆盖它指向的当前值。

于 2009-06-21T22:09:06.870 回答
1204

要同时添加多个键,请使用dict.update()

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

对于添加单个密钥,接受的答案具有较少的计算开销。

于 2009-07-22T14:48:17.997 回答
1186

我想整合有关 Python 词典的信息:

创建一个空字典

data = {}
# OR
data = dict()

创建具有初始值的字典

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

插入/更新单个值

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

插入/更新多个值

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

更新运算符 现在|=适用于字典:

data |= {'c':3,'d':4}

在不修改原件的情况下创建合并字典

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

这使用了一个称为字典解包的新功能。

data = {**data1, **data2, **data3}

Python 3.9+:

合并运算符 |现在适用于字典:

data = data1 | {'c':3,'d':4}

删除字典中的项目

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

检查一个键是否已经在字典中

key in data

遍历字典中的对

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

从两个列表创建字典

data = dict(zip(list_with_keys, list_with_values))
于 2011-12-05T06:07:36.293 回答
167

“是否可以在创建 Python 字典后为其添加键?它似乎没有 .add() 方法。”

是的,这是可能的,并且它确实有一个实现这一点的方法,但你不想直接使用它。

为了演示如何以及如何不使用它,让我们用 dict 文字创建一个空 dict {},:

my_dict = {}

最佳实践 1:下标符号

要使用单个新键和值更新此 dict,您可以使用提供项目分配的下标表示法(请参阅此处的映射) :

my_dict['new key'] = 'new value'

my_dict就是现在:

{'new key': 'new value'}

最佳实践 2:update方法 - 2 种方式

我们还可以使用方法有效地更新具有多个值update字典。我们可能在这里不必要地创建了一个额外的dict,所以我们希望我们dict已经创建并来自或用于其他目的:

my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})

my_dict就是现在:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}

使用 update 方法执行此操作的另一种有效方法是使用关键字参数,但由于它们必须是合法的 Python 单词,因此不能有空格或特殊符号或以数字开头的名称,但许多人认为这是一种更易读的方式为字典创建键,在这里我们当然避免创建额外的不必要的dict

my_dict.update(foo='bar', foo2='baz')

现在my_dict是:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}

所以现在我们已经介绍了三种 Pythonic 更新dict.


魔术方法,__setitem__以及为什么应该避免它

还有另一种更新dict你不应该使用的方法,它使用该__setitem__方法。这是一个如何使用该__setitem__方法将键值对添加到 adict的示例,并演示了使用它的性能不佳:

>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}


>>> def f():
...     d = {}
...     for i in xrange(100):
...         d['foo'] = i
... 
>>> def g():
...     d = {}
...     for i in xrange(100):
...         d.__setitem__('foo', i)
... 
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539

所以我们看到使用下标符号实际上比使用快得多__setitem__。做 Pythonic 的事情,即按照预期的方式使用语言,通常更具可读性和计算效率。

于 2014-11-29T23:57:59.250 回答
117
dictionary[key] = value
于 2009-06-21T22:08:57.477 回答
64

如果你想在字典中添加字典,你可以这样做。

示例:向您的字典和子字典添加一个新条目

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

输出:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

注意: Python 要求您首先添加一个子

dictionary["dictionary_within_a_dictionary"] = {}

在添加条目之前。

于 2012-04-26T19:04:33.870 回答
59

常规语法是d[key] = value,但如果您的键盘缺少方括号键,您也可以这样做:

d.__setitem__(key, value)

事实上,定义__getitem____setitem__方法是如何让自己的类支持方括号语法。请参阅深入了解Python,5.6。特殊类方法

于 2013-04-14T00:58:27.320 回答
42

您可以创建一个:

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

## example

myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)

给出:

>>> 
{'apples': 6, 'bananas': 3}
于 2013-05-25T13:33:35.353 回答
34

这个流行的问题解决了合并字典ab.

以下是一些更直接的方法(在 Python 3 中测试)...

c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

注意:上面的第一种方法只有在键b是字符串的情况下才有效。

要添加或修改单个元素b字典将只包含那个元素...

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

这相当于...

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )
于 2013-08-17T23:04:12.190 回答
30

假设您想生活在不可变的世界中,不想修改原始世界,但想要创建一个新的dict,这是向原始世界添加新密钥的结果。

在 Python 3.5+ 中,您可以执行以下操作:

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

Python 2 等价物是:

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

在其中任何一个之后:

params仍然等于{'a': 1, 'b': 2}

new_params等于{'a': 1, 'b': 2, 'c': 3}

有时您不想修改原始文件(您只想要添加到原始文件的结果)。我发现这是一个令人耳目一新的替代方案:

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

参考:`dict(d1, **d2)` 表达式中的 `**` 是什么意思?

于 2018-01-12T19:31:53.227 回答
24

还有一个名字奇怪,行为古怪,但仍然很方便的东西dict.setdefault()

value = my_dict.setdefault(key, default)

基本上只是这样做:

try:
    value = my_dict[key]
except KeyError: # key not found
    value = my_dict[key] = default

例如,

>>> mydict = {'a':1, 'b':2, 'c':3}
>>> mydict.setdefault('d', 4)
4 # returns new value at mydict['d']
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
# but see what happens when trying it on an existing key...
>>> mydict.setdefault('a', 111)
1 # old value was returned
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored
于 2017-10-23T14:03:24.300 回答
15

更新字典有两种方法:

  1. 使用方括号表示法 ( [])

    my_dict = {}
    my_dict['key'] = 'value'
    
  2. 使用update()方法

    my_dict = {}
    my_dict.update({'key': 'value'})
    
于 2021-08-31T13:20:21.347 回答
8

如果您没有加入两个字典,而是将新的键值对添加到字典中,那么使用下标表示法似乎是最好的方法。

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

但是,如果您想添加例如数千个新的键值对,您应该考虑使用该update()方法。

于 2018-10-11T08:57:34.223 回答
8

这个问题已经得到了令人作呕的回答,但是由于我的 评论 获得了很大的关注,所以这里是一个答案:

添加新密钥而不更新现有字典

如果您在这里试图弄清楚如何添加一个键并返回一个字典(不修改现有字典),您可以使用以下技术做到这一点

蟒蛇> = 3.5

new_dict = {**mydict, 'new_key': new_val}

蟒蛇 < 3.5

new_dict = dict(mydict, new_key=new_val)

请注意,使用这种方法,您的密钥将需要遵循python中有效标识符名称的规则。

于 2021-10-01T21:12:07.397 回答
7

这是我在这里没有看到的另一种方式:

>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}

您可以使用字典构造函数和隐式扩展来重建字典。此外,有趣的是,此方法可用于控制字典构建期间的位置顺序(Python 3.6 后)。事实上,对于 Python 3.7 及更高版本,插入顺序是有保证的!

>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>> 

以上是使用字典理解。

于 2019-11-19T04:57:20.903 回答
6

首先检查key是否已经存在:

a={1:2,3:4}
a.get(1)
2
a.get(5)
None

然后您可以添加新的键和值。

于 2019-03-25T13:01:25.417 回答
6

您可以使用方括号:

my_dict = {}
my_dict["key"] = "value"

或者您可以使用.update()方法:

my_another_dict = {"key": "value"}
my_dict = {}
my_dict.update(my_another_dict)
于 2021-04-16T05:18:29.473 回答
5

这里有一个简单的方法!

your_dict = {}
your_dict['someKey'] = 'someValue'

这将key: valueyour_dict字典中添加一对新的key = someKeyvalue = somevalue

如果键的值somekey已经存在于your_dict.

于 2021-01-13T11:16:32.063 回答
5
your_dict = {}

添加新密钥:

  1. your_dict[key]=value

  2. your_dict.update(key=value)

于 2021-01-18T20:34:21.997 回答
5

dict 类中存在一个应该适合您的更新方法。

考虑:

# dictionary = {"key":"value"}

但是没有任何方法,您可以通过创建一个新值来添加一个键,如下所示:

dictionary['newkey'] = 'newvalue'

或使用更新https://www.python.org/dev/peps/pep-0584/#dict-update

dictionary.update({'newkey':'newvalue'})
于 2021-12-28T21:12:57.210 回答
4

我认为指出 Python 的collections模块也很有用,该模块由许多有用的字典子类和包装器组成,它们简化了字典中数据类型的添加和修改,特别是defaultdict

调用工厂函数以提供缺失值的 dict 子类

如果您使用的字典总是包含相同的数据类型或结构,例如列表字典,这将特别有用。

>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})

如果键还不存在,defaultdict则将给定的值(在我们的例子中10)作为初始值分配给字典(通常在循环中使用)。因此,此操作做了两件事:它向字典添加一个新键(根据问题),在该键尚不存在时分配该值。使用标准字典,这会引发错误,因为+=操作正在尝试访问尚不存在的值:

>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key'

如果不使用defaultdict,添加新元素的代码量会更多,可能看起来像:

# This type of code would often be inside a loop
if 'key' not in example:
    example['key'] = 0  # add key and initial value to dict; could also be a list
example['key'] += 1  # this is implementing a counter

defaultdict也可以用于复杂的数据类型,例如listset

>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})

添加元素会自动初始化列表。

于 2019-08-27T21:21:02.760 回答
4

添加一个字典(键,值)类。

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        #self[key] = value # add new key and value overwriting any exiting same key
        if self.get(key)!=None:
            print('key', key, 'already used') # report if key already used
        self.setdefault(key, value) # if key exit do nothing


## example

myd = myDict()
name = "fred"

myd.add('apples',6)
print('\n', myd)
myd.add('bananas',3)
print('\n', myd)
myd.add('jack', 7)
print('\n', myd)
myd.add(name, myd)
print('\n', myd)
myd.add('apples', 23)
print('\n', myd)
myd.add(name, 2)
print(myd)
于 2020-02-04T01:47:50.377 回答
1

您可以像这样创建一个新的键值对:

my_dictionary = {"key1" : "value1"}
my_dictionary["key2"] = "value2"

要更改“key1”或“value2”,您可以执行相同的操作,如下所示:

my_dictionary = {"key1" : "value1"}
my_dictionary["key2"] = "value2"

my_dictionary["key1"] = "value1_revised"
于 2022-01-23T21:08:49.030 回答