如何向现有词典中添加关键字?它没有.add()方法。
当前回答
这个问题已经得到了令人恶心的回答,但自从我议论获得了很大的牵引力,以下是答案:
添加新密钥而不更新现有字典
如果您在这里试图找出如何添加键并返回新字典(而不修改现有字典),可以使用以下技术来完成
Python>=3.5
new_dict = {**mydict, 'new_key': new_val}
Python<3.5
new_dict = dict(mydict, new_key=new_val)
注意,使用这种方法,您的密钥需要遵循Python中有效标识符名称的规则。
其他回答
如果您想在字典中添加字典,可以这样做。
示例:向字典和子字典添加新条目
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"] = {}
在添加条目之前。
我想整合有关Python字典的信息:
创建空词典
data = {}
# OR
data = dict()
使用初始值创建字典
data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}
插入/更新单个值
data['a'] = 1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
插入/更新多个值
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Python 3.9+:
更新运算符|=现在适用于字典:
data |= {'c':3,'d':4}
创建合并词典而不修改原始词典
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
Python 3.5+:
这使用了一个名为字典解包的新功能。
data = {**data1, **data2, **data3}
Python 3.9+:
合并运算符|现在适用于字典:
data = data1 | {'c':3,'d':4}
删除字典中的项目
del data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
检查字典中是否已存在密钥
key in data
遍历字典中的成对项
for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
从两个列表创建词典
data = dict(zip(list_with_keys, list_with_values))
还有一个名字奇怪,行为怪异,但仍然很方便的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
让我们假设你想生活在一个不可变的世界中,不想修改原来的内容,而是想创建一个新的dict,这是向原来的内容添加新密钥的结果。
在Python 3.5+中,您可以执行以下操作:
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
Python 2的等价物是:
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
在执行以下任一操作之后:
params仍然等于{‘a‘:1,‘b‘:2}
and
new_params等于{‘a‘:1,‘b‘:2,‘c‘:3}
有时您不想修改原始文件(您只想得到添加到原始文件的结果)。我觉得这是一个令人耳目一新的替代方案:
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
or
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})
参考文献:在表达式“dict(d1,**d2)”中,“**”是什么意思?
这个问题已经得到了令人恶心的回答,但自从我议论获得了很大的牵引力,以下是答案:
添加新密钥而不更新现有字典
如果您在这里试图找出如何添加键并返回新字典(而不修改现有字典),可以使用以下技术来完成
Python>=3.5
new_dict = {**mydict, 'new_key': new_val}
Python<3.5
new_dict = dict(mydict, new_key=new_val)
注意,使用这种方法,您的密钥需要遵循Python中有效标识符名称的规则。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录