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


当前回答

dictionary[key] = value

其他回答

通过为字典中的键指定值,可以在字典中创建新的键/值对

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

如果键不存在,则添加该键并指向该值。如果它存在,它所指向的当前值将被覆盖。

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

dico[“new key”]=“value”

dictionary[key] = value