How can I add new keys to a dictionary?

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

    If you want to add a dictionary within a dictionary you can do it this way.

    Example: Add a new entry to your dictionary & sub dictionary

    dictionary = {}
    dictionary["new key"] = "some new entry" # add new dictionary entry
    dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
    dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
    print (dictionary)
    

    Output:

    {'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
    

    NOTE: Python requires that you first add a sub

    dictionary["dictionary_within_a_dictionary"] = {}
    

    before adding entries.

提交回复
热议问题