Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向字典添加新键?_Python_Dictionary_Lookup - Fatal编程技术网

Python 如何向字典添加新键?

Python 如何向字典添加新键?,python,dictionary,lookup,Python,Dictionary,Lookup,在Python字典创建之后,是否可以向它添加一个键 它似乎没有一个.add()方法。您可以通过为字典中的键分配一个值来创建一个新的键/值对 dictionary[key] = value d = {'key': 'value'} print(d) # {'key': 'value'} d['mynewkey'] = 'mynewvalue' print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'} 如果该键不存在,则会添加该键并指向该

在Python字典创建之后,是否可以向它添加一个键


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

您可以通过为字典中的键分配一个值来创建一个新的键/值对

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

d['mynewkey'] = 'mynewvalue'

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

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

要同时添加多个键,请使用:


对于添加单个键,接受的答案的计算开销较小。

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

data |= {'c':3,'d':4}
data = data1 | {'c':3,'d':4}
创建空字典 使用初始值创建字典 插入/更新单个值 插入/更新多个值 Python 3.9+: 更新操作符
|=
现在适用于字典:

data |= {'c':3,'d':4}
data = data1 | {'c':3,'d':4}
创建合并词典而不修改原始词典 Python 3.5+: 这使用了一种称为字典解包的新功能

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

data |= {'c':3,'d':4}
data = data1 | {'c':3,'d':4}
删除字典中的项目 检查字典中是否已有密钥 在字典中遍历对 从两个列表中创建词典
如果你想在字典中添加字典,你可以这样做

示例:向词典和子词典添加新条目

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'}}}
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
注意:Python要求您首先添加子对象

dictionary["dictionary_within_a_dictionary"] = {}

添加条目之前。

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

d.__setitem__(key, value)
事实上,定义
\uuuu getitem\uuuuuu
\uuuuu setitem\uuuuuuu
方法可以使您自己的类支持方括号语法。请参见,您可以创建一个:

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}
介绍合并字典
a
b
的功能方法

下面是一些更简单的方法(在Python 3中测试)

注:上述第一种方法仅在
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' )
“是否可以在Python字典创建后向其添加键?它似乎没有.add()方法。” 是的,这是可能的,它确实有一个实现这个的方法,但是你不想直接使用它

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

my_dict = {}
最佳实践1:下标表示法 要使用单个新键和值更新此dict,可以使用提供项目分配的:

my_dict['new key'] = 'new value'
my_dict
现在是:

{'new key': 'new value'}
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}
最佳实践2:
更新
方法-2种方法 我们还可以使用多个值高效地更新dict。我们可能在这里不必要地创建了一个额外的
dict
,因此我们希望我们的
dict
已经创建并来自或用于其他目的:

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

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

另一种使用UPDATE方法的有效方法是使用关键字参数,但由于它们必须是合法的Python字,所以不能有空格或特殊符号或用数字来启动名称,但许多人认为这是为DICT创建密钥的更可读的方式,在这里,我们当然避免创建额外的不必要的

dict

my_dict.update(foo='bar', foo2='baz')
my_dict
现在是:

{'new key': 'new value'}
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}
现在我们已经介绍了更新dict的三种Pythonic方法

your_dict = {}

神奇的方法,
\uuuuuu setitem\uuuuuu
,以及为什么应该避免它 还有另一种更新不应该使用的
dict
的方法,它使用
\uuuu setitem\uuuu
方法。下面是一个示例,演示了如何使用
\uu setitem\uuu
方法将键值对添加到
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

因此,我们看到使用下标表示法实际上比使用
\uuuu setitem\uuuu
快得多。做Pythonic的事情,也就是按照预期的方式使用语言,通常可读性和计算效率都更高。

这么多答案,但每个人仍然忘记了命名奇怪、行为怪异、但仍然很方便的dict.setdefault()

这个

基本上就是这样:

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


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

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

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
Python 2的等价物是:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
在以下任一项之后:

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

new_参数
等于
{'a':1,'b':2,'c':3}

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

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3


参考:

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

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

但是,如果您想添加数千个新的键值对,则应该考虑使用<代码> UpDebug()/<代码>方法。

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

dictionary[key] = value
a={1:2,3:4}
a.get(1)
2
a.get(5)
None

然后您可以添加新的键和值,我认为指出Python的模块也会很有用,它由许多有用的字典子类和包装器组成,简化了字典中数据类型的添加和修改,具体来说:

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

如果您使用的词典总是
my_dict={}
my_dict["key"]="value"
my_another_dict={"key":"value"}
my_dict={}
my_dict.update(my_another_dict)
d1 = {"name": "Arun", "height": 170}
d2 = {"age": 21, "height": 170}
d3 = d1 | d2 # d3 is the union of d1 and d2
print(d3)
{'name': 'Arun', 'height': 170, 'age': 21}
d1 |= d2
print(d1)
{'name': 'Arun', 'height': 170, 'age': 21}
d1 |= {"weight": 80}
print(d1)
{'name': 'Arun', 'height': 170, 'age': 21, 'weight': 80}