Updating nested dictionaries when data has existing key

前端 未结 5 715
感动是毒
感动是毒 2020-12-08 22:22

I am trying to update values in a nested dictionary, without over-writting previous entries when the key already exists. For example, I have a dictionary:

           


        
5条回答
  •  清歌不尽
    2020-12-08 23:28

    You can use collections.defaultdict for this, and just set the key-value pairs within the nested dictionary.

    from collections import defaultdict
    my_dict = defaultdict(dict)
    my_dict['myKey']['nestedDictKey1'] = a_value
    my_dict['myKey']['nestedDictKey2'] = another_value
    

    Alternatively, you can also write those last 2 lines as

    my_dict['myKey'].update({"nestedDictKey1" : a_value })
    my_dict['myKey'].update({"nestedDictKey2" : another_value })
    

提交回复
热议问题