How can I add new keys to a dictionary?

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

    The conventional syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could also do:

    d.__setitem__(key, value)
    

    In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php

提交回复
热议问题