How can I add new keys to a dictionary?

前端 未结 16 2678
梦毁少年i
梦毁少年i 2020-11-22 00:40

Is it possible to add a key to a Python dictionary after it has been created?

It doesn\'t seem to have an .add() method.

16条回答
  •  别那么骄傲
    2020-11-22 01:12

    add dictionary key, value class.

    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)
    

提交回复
热议问题