How can I add new keys to a dictionary?

前端 未结 16 2645
梦毁少年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:13

    You can create one:

    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)
    

    Gives:

    >>> 
    {'apples': 6, 'bananas': 3}
    

提交回复
热议问题