如何向现有词典中添加关键字?它没有.add()方法。
当前回答
dico[“new key”]=“value”
其他回答
还有一个名字奇怪,行为怪异,但仍然很方便的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
您可以创建一个:
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}
常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:
d.__setitem__(key, value)
事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。
这个流行的问题涉及合并字典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字典的信息:
创建空词典
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))