How can I add new keys to a dictionary?

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

    If you're not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.

    import timeit
    
    timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
    >> 0.49582505226135254
    
    timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
    >> 0.20782899856567383
    

    However, if you'd like to add, for example, thousands of new key-value pairs, you should consider using the update() method.

提交回复
热议问题