如何向字典中添加新键?
- 2024-12-03 08:44:00
- admin 原创
- 182
问题描述:
如何向现有字典中添加新键?没有方法.add()
。
解决方案 1:
您可以通过为该键分配一个值来在字典中创建新的键/值对
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
如果该键不存在,则添加该键并指向该值。如果该键存在,则覆盖其指向的当前值。
解决方案 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'
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))
解决方案 3:
要同时添加多个键,请使用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}
对于添加单个键,接受的答案具有较少的计算开销。
解决方案 4:
“创建 Python 字典后是否可以添加键?它似乎没有 .add() 方法。”
是的,这是可能的,并且它确实有一个实现这一点的方法,但你不想直接使用它。
为了演示如何使用和不使用它,让我们用字典文字创建一个空字典{}
:
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'}
使用更新方法执行此操作的另一种有效方法是使用关键字参数,但由于它们必须是合法的 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__
方法来向 中添加键值对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 的方式使用语言,即按照预期的方式使用语言,通常更易读且计算效率更高。
解决方案 5:
dictionary[key] = value
解决方案 6:
常规语法是d[key] = value
,但如果您的键盘没有方括号键,您也可以执行以下操作:
d.__setitem__(key, value)
事实上,定义__getitem__
和__setitem__
方法是让你自己的类支持方括号语法的方法。请参阅深入 Python,像字典一样工作的类。
解决方案 7:
如果您想在字典中添加字典,您可以通过这种方式进行。
示例:向词典和子词典中添加新条目
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"] = {}
在添加条目之前。
解决方案 8:
您可以创建一个:
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}
解决方案 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})
参考:表达式 dict(d1, **d2)
中的 **
是什么意思?
解决方案 10:
这个热门问题涉及合并字典和的功能方法。a
`b`
以下是一些更直接的方法(在 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' )
解决方案 11:
还有名字奇怪、行为怪异但仍然方便的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
解决方案 12:
这个问题已经被回答得令人厌烦了,但由于我的(现已删除)
评论
获得了很大的关注,所以这里是答案:
添加新键而不更新现有字典
如果你在这里试图弄清楚如何添加一个键并返回一个新字典(不修改现有的字典),你可以使用下面的技术来实现
Python >= 3.5
new_dict = {**mydict, 'new_key': new_val}
Python < 3.5
new_dict = dict(mydict, new_key=new_val)
请注意,使用此方法,您的密钥需要遵循Python 中有效标识符名称的规则。
解决方案 13:
如果您不是要合并两个字典,而是向字典中添加新的键值对,那么使用下标符号似乎是最好的方法。
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()
方法。
解决方案 14:
这是我在这里没有看到的另一种方法:
>>> 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}
>>>
以上是使用字典理解。
解决方案 15:
首先检查键是否已经存在:
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
然后您可以添加新的键和值。
解决方案 16:
添加一个字典(键,值)类。
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('
', myd)
myd.add('bananas',3)
print('
', myd)
myd.add('jack', 7)
print('
', myd)
myd.add(name, myd)
print('
', myd)
myd.add('apples', 23)
print('
', myd)
myd.add(name, 2)
print(myd)
解决方案 17:
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
还可以与复杂数据类型一起使用,list
例如set
:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
添加元素会自动初始化列表。
解决方案 18:
不使用 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))
解决方案 19:
update()
和就地合并运算符 ( |=
)
|=
字典也可以通过update()
元组列表进行就地更新 。
d = {'a': 1}
d |= [('b', 2), ('c', 3)]
# or
d.update([('b', 2), ('c', 3)])
print(d) # {'a': 1, 'b': 2, 'c': 3}
不仅比|=
更简洁update
,而且速度更快。例如,如果一个字典由长度为 5 的字典更新,|=
则比 快近 30% update()
(反过来也比循环快)(在 Python 3.9.12 上测试)。
import timeit
setup = "pairs = list(zip(range(5), range(5)))"
t1 = min(timeit.repeat("d={}
d.update(pairs)", setup)) # 0.41770019999239594
t2 = min(timeit.repeat("d={}
for k,v in pairs: d[k] = v", setup)) # 0.5213192999945022
t3 = min(timeit.repeat("d={}
d |= pairs", setup)) # 0.3178639999969164
向嵌套字典中添加新键
如果必须将一个键添加到嵌套在字典中的字典中,则dict.setdefault
(或collections.defaultdict
)非常有用。例如,让我们尝试将新的键值对添加到mydict
仅嵌套在另一个键中:'address'
。
mydict = {'id': {'id_num': 'xxxx', 'url': 'www.example.com'}}
mydict['address']['work'] = '123 A St' # <---- KeyError: 'address'
然后可以通过两行获得所需的输出(首先在 下初始化一个空字典'address'
):
mydict['address'] = {}
mydict['address']['work'] = '123 A St' # <---- OK
或者可以通过以下方式一步完成dict.setdefault()
:
mydict.setdefault('address', {})['work'] = '123 A St' # <---- OK
它之所以有效,是因为{}
向其中传递了一个空字典()的默认值.setdefault
,因此当需要向其中添加键值对时,它已经被初始化了。
解决方案 20:
您可以编写一个函数来执行此操作,例如:
def dict_ins( d, key, value ):
if key in d: raise Exception('This key is already in the dictionary.')
d[key] = value