如何向字典添加新键?

内容 隐藏

问题:如何向字典添加新键?

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

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

Is it possible to add a key to a Python dictionary after it has been created?

It doesn’t seem to have an .add() method.


回答 0

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

回答 1

要同时添加多个键,请使用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}

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

To add multiple keys simultaneously, use 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}

For adding a single key, the accepted answer has less computational overhead.


回答 2

我想整合有关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'

创建合并字典而无需修改原始字典

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

删除字典中的项目

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

Python 3.5的新功能

创建合并字典而不修改原始字典:

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

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

Python 3.9的新功能

更新或添加现有字典的值

现在,更新运算符 |=可用于词典:

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

创建合并字典而无需修改原始字典

合并操作 |现在工作的字典:

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

随时添加更多!

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

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

Inserting/Updating a single value

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)

Inserting/Updating multiple values

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

Creating a merged dictionary without modifying originals

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

Deleting items in dictionary

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

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

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

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))

New to Python 3.5

Creating a merged dictionary without modifying originals:

This uses a new featrue called dictionary unpacking.

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

New to Python 3.9

Update or add values for an existing dictionary

The update operator |= now works for dictionaries:

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

Creating a merged dictionary without modifying originals

The merge operator | now works for dictionaries:

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

Feel free to add more!


回答 3

“创建密钥后是否可以向Python字典添加密钥?它似乎没有.add()方法。”

是的,这是可能的,并且它确实具有实现此目的的方法,但是您不想直接使用它。

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

my_dict = {}

最佳实践1:下标符号

要使用单个新键和值更新此字典,可以使用下标符号(请参见此处的映射)提供项目分配:

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

因此,现在我们介绍了三种更新Python的Python方法dict


魔术方法,__setitem__以及为什么应避免使用

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

>>> 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__。做Python式的事情,也就是说,按照预期的方式使用该语言,通常既可读性强又计算效率高。

“Is it possible to add a key to a Python dictionary after it has been created? It doesn’t seem to have an .add() method.”

Yes it is possible, and it does have a method that implements this, but you don’t want to use it directly.

To demonstrate how and how not to use it, let’s create an empty dict with the dict literal, {}:

my_dict = {}

Best Practice 1: Subscript notation

To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:

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

my_dict is now:

{'new key': 'new value'}

Best Practice 2: The update method – 2 ways

We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:

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

my_dict is now:

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

Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can’t have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict:

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

and my_dict is now:

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

So now we have covered three Pythonic ways of updating a dict.


Magic method, __setitem__, and why it should be avoided

There’s another way of updating a dict that you shouldn’t use, which uses the __setitem__ method. Here’s an example of how one might use the __setitem__ method to add a key-value pair to a dict, and a demonstration of the poor performance of using it:

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

So we see that using the subscript notation is actually much faster than using __setitem__. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.


回答 4

dictionary[key] = value
dictionary[key] = value

回答 5

如果要在字典中添加字典,可以使用此方法。

示例:将新条目添加到词典和子词典中

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"] = {}

在添加条目之前。

If you want to add a dictionary within a dictionary you can do it this way.

Example: Add a new entry to your dictionary & sub dictionary

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)

Output:

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

NOTE: Python requires that you first add a sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.


回答 6

正统语法为d[key] = value,但是如果键盘缺少方括号键,则可以执行以下操作:

d.__setitem__(key, value)

实际上,定义__getitem____setitem__方法是使自己的类支持方括号语法的方法。参见https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_linked_framework/special_class_methods.php

The orthodox syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could 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 https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php


回答 7

您可以创建一个:

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}

You can create one:

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)

Gives:

>>> 
{'apples': 6, 'bananas': 3}

回答 8

这个受欢迎的问题解决了合并词典和语法的功能方法。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' )

This popular question addresses functional methods of merging dictionaries a and b.

Here are some of the more straightforward methods (tested in 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() )

Note: The first method above only works if the keys in b are strings.

To add or modify a single element, the b dictionary would contain only that one element…

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

This is equivalent to…

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

c = functional_dict_add( a, 'd', 'dog' )

回答 9

假设您想生活在不可变的世界中,不想修改原始文件,而是想创建一个新文件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})

参考:https : //stackoverflow.com/a/2255892/514866

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}

and

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

or

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

Reference: https://stackoverflow.com/a/2255892/514866


回答 10

如此众多的答案,仍然让每个人都忘记了这个名字奇怪,举止古怪而又方便的地方 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

So many answers and still everybody forgot about the strangely named, oddly behaved, and yet still handy dict.setdefault()

This

value = my_dict.setdefault(key, default)

basically just does this:

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

e.g.

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

回答 11

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

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()方法。

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.


回答 12

我认为collections指出由许多有用的字典子类和包装器组成的Python 模块也是有用的,这些子类和包装器简化了字典中数据类型添加和修改,特别是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]})

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

I think it would also be useful to point out Python’s collections module that consists of many useful dictionary subclasses and wrappers that simplify the addition and modification of data types in a dictionary, specifically defaultdict:

dict subclass that calls a factory function to supply missing values

This is particularly useful if you are working with dictionaries that always consist of the same data types or structures, for example a dictionary of lists.

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

If the key does not yet exist, defaultdict assigns the value given (in our case 10) as the initial value to the dictionary (often used inside loops). This operation therefore does two things: it adds a new key to a dictionary (as per question), and assigns the value if the key doesn’t yet exist. With the standard dictionary, this would have raised an error as the += operation is trying to access a value that doesn’t yet exist:

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

Without the use of defaultdict, the amount of code to add a new element would be much greater and perhaps looks something like:

# 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 can also be used with complex data types such as list and set:

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

Adding an element automatically initialises the list.


回答 13

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

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

上面是使用字典理解的。

Here’s another way that I didn’t see here:

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

You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

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

The above is using dictionary comprehension.


回答 14

首先检查密钥是否已经存在

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

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

first to check whether the key already exists

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

then you can add the new key and value


回答 15

添加字典键,值类。

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)

add dictionary key, value class.

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)