如何向现有词典中添加关键字?它没有.add()方法。
当前回答
常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:
d.__setitem__(key, value)
事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。
其他回答
您可以创建一个:
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
## example
myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)
给予:
>>>
{'apples': 6, 'bananas': 3}
这是我在这里没有看到的另一种方式:
>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}
可以使用字典构造函数和隐式扩展来重建字典。此外,有趣的是,这种方法可以用于控制字典构建期间的位置顺序(Python 3.6之后)。事实上,Python 3.7和更高版本保证了插入顺序!
>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>>
以上是使用字典理解。
如果您想在字典中添加字典,可以这样做。
示例:向字典和子字典添加新条目
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)
输出:
{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
注意:Python要求您首先添加子
dictionary["dictionary_within_a_dictionary"] = {}
在添加条目之前。
常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:
d.__setitem__(key, value)
事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。
dictionary[key] = value