如何向现有词典中添加关键字?它没有.add()方法。


当前回答

还有一个名字奇怪,行为怪异,但仍然很方便的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

其他回答

这个流行的问题涉及合并字典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' )
dictionary[key] = value

dico[“new key”]=“value”

常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:

d.__setitem__(key, value)

事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。

添加字典(键、值)类。

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('\n', myd)
myd.add('bananas',3)
print('\n', myd)
myd.add('jack', 7)
print('\n', myd)
myd.add(name, myd)
print('\n', myd)
myd.add('apples', 23)
print('\n', myd)
myd.add(name, 2)
print(myd)