建立密鑰後,是否能夠向Python字典添加密鑰? 它彷佛沒有.add()
方法。 php
dictionary[key] = value
d = {'key':'value'} print(d) # {'key': 'value'} d['mynewkey'] = 'mynewvalue' print(d) # {'mynewkey': 'mynewvalue', 'key': 'value'}
若是要在字典中添加字典,能夠使用此方法。 python
示例:將新條目添加到詞典和子詞典中 ui
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)
輸出: this
{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
注意: Python要求您首先添加一個子 加密
dictionary["dictionary_within_a_dictionary"] = {}
在添加條目以前。 spa
要同時添加多個鍵: code
>>> x = {1:2} >>> print x {1: 2} >>> d = {3:4, 5:6, 7:8} >>> x.update(d) >>> print x {1: 2, 3: 4, 5: 6, 7: 8}
對於添加單個密鑰,可接受的答案具備較少的計算開銷。 ci
正統語法爲d[key] = value
,可是若是鍵盤缺乏方括號鍵,則能夠執行如下操做: get
d.__setitem__(key, value)
實際上,定義__getitem__
和__setitem__
方法是使本身的類支持方括號語法的方法。 參見https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_linked_framework/special_class_methods.php it