如何向现有词典中添加关键字?它没有.add()方法。
当前回答
常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:
d.__setitem__(key, value)
事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。
其他回答
首先检查密钥是否已存在:
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
然后可以添加新的键和值。
如果您想在字典中添加字典,可以这样做。
示例:向字典和子字典添加新条目
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"] = {}
在添加条目之前。
dictionary[key] = value
还有一个名字奇怪,行为怪异,但仍然很方便的dict.setdefault()。
This
value = my_dict.setdefault(key, default)
基本上就是这样:
try:
value = my_dict[key]
except KeyError: # key not found
value = my_dict[key] = default
例如。,
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> mydict.setdefault('d', 4)
4 # returns new value at mydict['d']
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
# but see what happens when trying it on an existing key...
>>> mydict.setdefault('a', 111)
1 # old value was returned
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored
您可以创建一个:
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}
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字