简体   繁体   English

如何向字典添加新键?

[英]How can I add new keys to a dictionary?

How do I add a key to an existing dictionary?如何向现有字典添加键? It doesn't have an .add() method.它没有.add()方法。

You create a new key/value pair on a dictionary by assigning a value to that key您通过为该键分配一个值来在字典上创建一个新的键/值对

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

d['mynewkey'] = 'mynewvalue'

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

If the key doesn't exist, it's added and points to that value.如果键不存在,则添加并指向该值。 If it exists, the current value it points to is overwritten.如果存在,则覆盖它指向的当前值。

To add multiple keys simultaneously, usedict.update() :要同时添加多个键,请使用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.对于添加单个密钥,接受的答案具有较少的计算开销。

I feel like consolidating info about Python dictionaries:我想整合有关 Python 词典的信息:

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'

Python 3.9+: Python 3.9+:

The update operator |= now works for dictionaries:更新运算符|=现在适用于字典:

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

Creating a merged dictionary without modifying originals在不修改原件的情况下创建合并字典

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

Python 3.5+: Python 3.5+:

This uses a new feature called dictionary unpacking .这使用了一个称为字典解包的新功能。

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

Python 3.9+: Python 3.9+:

The merge operator |合并运算符| now works for dictionaries:现在适用于字典:

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

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

"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." “是否可以在创建 Python 字典后为其添加键?它似乎没有 .add() 方法。”

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最佳实践 1:下标符号

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

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

my_dict is now: my_dict现在是:

{'new key': 'new value'}

Best Practice 2: The update method - 2 ways最佳实践 2: update方法 - 2 种方式

We can also update the dict with multiple values efficiently as well using the update method .我们还可以使用update方法有效地更新具有多个值的字典。 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:我们可能在这里不必要地创建了一个额外的dict ,所以我们希望我们的dict已经被创建并来自或被用于其他目的:

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

my_dict is now: my_dict现在是:

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

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

and my_dict is now: my_dict现在是:

{'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 .所以现在我们已经介绍了更新dict的三种 Pythonic 方式。


Magic method, __setitem__ , and why it should be avoided魔术方法, __setitem__ ,以及为什么应该避免它

There's another way of updating a dict that you shouldn't use, which uses the __setitem__ method.还有另一种更新不应该使用的dict的方法,它使用__setitem__方法。 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:这是一个如何使用__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

So we see that using the subscript notation is actually much faster than using __setitem__ .所以我们看到使用下标符号实际上比使用__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.做 Pythonic 的事情,即按照预期的方式使用语言,通常更具可读性和计算效率。

dictionary[key] = value

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注意: Python 要求您首先添加一个子

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.在添加条目之前。

The conventional syntax is d[key] = value , but if your keyboard is missing the square bracket keys you could also do:常规语法是d[key] = value ,但如果您的键盘缺少方括号键,您也可以这样做:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax.事实上,定义__getitem____setitem__方法可以让您自己的类支持方括号语法。 See Dive Into Python, Classes That Act Like Dictionaries .请参阅Dive Into Python, Classes That Act Like Dictionaries

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}

This popular question addresses functional methods of merging dictionaries a and b . 这个流行的问题解决了合并字典ab函数方法。

Here are some of the more straightforward methods (tested in Python 3)...以下是一些更直接的方法(在 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.注意:上面的第一种方法只有在b中的键是字符串时才有效。

To add or modify a single element , the b dictionary would contain only that one element...要添加或修改单个元素b字典将只包含那个元素...

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

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.假设您想生活在不可变的世界中,并且不想修改原始内容,但想创建一个新的dict ,该字典是向原始内容添加新键的结果。

In Python 3.5+ you can do:在 Python 3.5+ 中,您可以执行以下操作:

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

The Python 2 equivalent is: Python 2 等价物是:

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

After either of these:在其中任何一个之后:

params is still equal to {'a': 1, 'b': 2} params仍然等于{'a': 1, 'b': 2}

and

new_params is equal to {'a': 1, 'b': 2, 'c': 3} new_params等于{'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: What does `**` mean in the expression `dict(d1, **d2)`?参考: `dict(d1, **d2)` 表达式中的 `**` 是什么意思?

There is also the strangely named, oddly behaved, and yet still handydict.setdefault() .还有一个奇怪的名字,奇怪的行为,但仍然很方便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

Eg,例如,

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

This question has already been answered ad nauseam, but since my comment gained a lot of traction, here it is as an answer:这个问题已经得到了令人作呕的回答,但是由于我的评论获得了很大的关注,所以这里是一个答案:

Adding new keys without updating the existing dict添加新密钥而不更新现有字典

If you are here trying to figure out how to add a key and return a new dictionary (without modifying the existing one), you can do this using the techniques below如果您在这里试图弄清楚如何添加一个键并返回一个字典(不修改现有字典),您可以使用以下技术做到这一点

python >= 3.5蟒蛇> = 3.5

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

python < 3.5蟒蛇 < 3.5

new_dict = dict(mydict, new_key=new_val)

Note that with this approach, your key will need to follow the rules of valid identifier names in python.请注意,使用这种方法,您的密钥将需要遵循 python 中有效标识符名称的规则

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.但是,如果您想添加例如数千个新的键值对,您应该考虑使用update()方法。

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 ).此外,有趣的是,此方法可用于控制字典构建期间的位置顺序( Python 3.6 后)。 In fact, insertion order is guaranteed for Python 3.7 and above! 事实上,对于 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}
>>> 

The above is using dictionary comprehension.以上是使用字典理解。

First to check whether the key already exists:首先检查key是否已经存在:

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

Then you can add the new key and value.然后您可以添加新的键和值。

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

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

dict subclass that calls a factory function to supply missing values调用工厂函数以提供缺失值的 dict 子类

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).如果键还不存在, defaultdict将给定的值(在我们的例子中为10 )作为初始值分配给字典(通常在循环中使用)。 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:如果不使用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 can also be used with complex data types such as list and set : defaultdict也可以用于复杂的数据类型,例如listset

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

Adding an element automatically initialises the list.添加元素会自动初始化列表。

You can use square brackets:您可以使用方括号:

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

Or you can use the .update() method:或者你可以使用.update()方法:

my_another_dict = {"key": "value"}
my_dict = {}
my_dict.update(my_another_dict)

Here is an easy way!这里有一个简单的方法!

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

This will add a new key: value pair in the your_dict dictionary with key = someKey and value = somevalue这将在your_dict字典中添加一个新的key: value对, key = someKeyvalue = somevalue

You can also use this way to update the value of the key somekey if that already exists in the your_dict .你也可以用这种方式来更新密钥的值somekey如果已经在存在your_dict

your_dict = {}

要添加新密钥:

  1. your_dict[key]=value

  2. your_dict.update(key=value)

There are two ways to update a dictionary:有两种方法可以更新字典:

  1. Use the square bracket notation ( [] )使用方括号表示法 ( [] )

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

    my_dict = {} my_dict.update({'key': 'value'})

Adding keys to dictionary without using add在不使用 add 的情况下将键添加到字典

        # Inserting/Updating single value
        # subscript notation method
        d['mynewkey'] = 'mynewvalue' # Updates if 'a' exists, else adds 'a'
        # OR
        d.update({'mynewkey': 'mynewvalue'})
        # OR
        d.update(dict('mynewkey'='mynewvalue'))
        # OR
        d.update('mynewkey'='mynewvalue')
        print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}
        # To add/update multiple keys simultaneously, use d.update():
        x = {3:4, 5:6, 7:8}
        d.update(x)
        print(d) # {'key': 'value', 'mynewkey': 'mynewvalue', 3: 4, 5: 6, 7: 8}
        # update operator |= now works for dictionaries:
        d |= {'c':3,'d':4}
        # Assigning new key value pair using dictionary unpacking.
        data1 = {4:6, 9:10, 17:20}
        data2 = {20:30, 32:48, 90:100}
        data3 = { 38:"value", 99:"notvalid"}
        d = {**data1, **data2, **data3}
        # The merge operator | now works for dictionaries:
        data = data1 | {'c':3,'d':4}
        # Create a dictionary from two lists
        data = dict(zip(list_with_keys, list_with_values))

Is it possible to add a key to a Python dictionary after it has been created?是否可以在创建后向 Python 字典添加键?

It doesn't seem to have an .add() method.它似乎没有.add()方法。

There exist an update method in the dict class that should works for you. dict 类中有一个更新方法应该适合你。

Considering:考虑:

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

But without any method you can add a key simply by creating a new value like the line below:但是没有任何方法,您可以简单地通过创建一个新值来添加一个键,如下行:

dictionary['newkey'] = 'newvalue'

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

dictionary.update({'newkey':'newvalue'})

You can make a new key, value pair like this:您可以像这样创建一个新的键值对:

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

To change "key1" or "value2" you can do the same thing, like this:要更改“key1”或“value2”,您可以执行相同的操作,如下所示:

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

my_dictionary["key1"] = "value1_revised"

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

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