如何向现有词典中添加关键字?它没有.add()方法。
当前回答
这个流行的问题涉及合并字典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' )
其他回答
这个流行的问题涉及合并字典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' )
“是否可以在Python字典创建后向其添加键?它似乎没有.add()方法。”
是的,这是可能的,它确实有一个实现这一点的方法,但您不想直接使用它。
为了演示如何使用和如何不使用它,让我们使用dict文本{}创建一个空dict:
my_dict = {}
最佳实践1:下标表示法
要用一个新的键和值更新此dict,可以使用提供项分配的下标表示法(请参阅此处的映射):
my_dict['new key'] = 'new value'
my_dict现在是:
{'new key': 'new value'}
最佳实践2:更新方法-2种方式
我们还可以使用更新方法高效地使用多个值更新dict。我们可能在这里不必要地创建了一个额外的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创建键的更易读的方法,在这里我们当然避免创建额外的不必要的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方式来更新字典。
魔术方法__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__快得多。做Pythonic的事情,也就是说,按照预期的方式使用语言,通常既可读性更高,计算效率也更高。
如果您不是在连接两个字典,而是在字典中添加新的键值对,那么使用下标表示法似乎是最好的方法。
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()方法。
还有一个名字奇怪,行为怪异,但仍然很方便的dict.setdefault()。
This
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
我想整合有关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))