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 datadata3.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 dictionarydata.pop(key) # Removes the key & returns the valuedata.clear() # Clears entire dictionary
检查一个键是否已经在字典中
key in data
在字典中遍历对
for key in data: # Iterates just through the keys, ignoring the valuesfor key, value in d.items(): # Iterates through the pairsfor key in d.keys(): # Iterates just through key, ignoring the valuesfor value in d.values(): # Iterates just through value, ignoring the keys
从两个列表创建字典
data = dict(zip(list_with_keys, list_with_values))
c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878c = 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] = valuereturn temp
c = functional_dict_add( a, 'd', 'dog' )
>>> 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
>>> 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
>>> example = dict()>>> example['key'] += 1Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 'key'
如果不使用defaultdict,添加新元素的代码量会大得多,可能看起来像这样:
# This type of code would often be inside a loopif 'key' not in example:example['key'] = 0 # add key and initial value to dict; could also be a listexample['key'] += 1 # this is implementing a counter
defaultdict也可以用于复杂的数据类型,例如list和set:
>>> example = defaultdict(list)>>> example['key'].append(1)>>> exampledefaultdict(<class 'list'>, {'key': [1]})