向字典添加新键?

建立密钥后,是否能够向Python字典添加密钥? 它彷佛没有.add()方法。 php


#1楼

dictionary[key] = value

#2楼

d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}

#3楼

若是要在字典中添加字典,能够使用此方法。 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


#4楼

要同时添加多个键: 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


#5楼

正统语法为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

相关文章
相关标签/搜索