如何向现有词典中添加关键字?它没有.add()方法。
当前回答
“是否可以在Python字典创建后向其添加键?它似乎没有.add()方法。”
是的,这是可能的,它确实有一个实现这一点的方法,但您不想直接使用它。
为了演示如何使用和如何不使用它,让我们使用dict文本{}创建一个空dict:
my_dict = {}
最佳实践1:下标表示法
要用一个新的键和值更新此dict,可以使用提供项分配的下标表示法(请参阅此处的映射):
my_dict['new key'] = 'new value'
my_dict现在是:
{'new key': 'new value'}
最佳实践2:更新方法-2种方式
我们还可以使用更新方法高效地使用多个值更新dict。我们可能在这里不必要地创建了一个额外的dict,所以我们希望我们的dict已经创建,并且来自或用于其他目的:
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
my_dict现在是:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
使用update方法实现这一点的另一种有效方法是使用关键字参数,但由于它们必须是合法的python单词,因此不能使用空格或特殊符号,也不能以数字开头名称,但许多人认为这是为dict创建键的更易读的方法,在这里我们当然避免创建额外的不必要的dict:
my_dict.update(foo='bar', foo2='baz')
my_dict现在是:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value',
'foo': 'bar', 'foo2': 'baz'}
因此,现在我们已经介绍了三种Python方式来更新字典。
魔术方法__setitem__,以及为什么应该避免它
还有另一种不应该使用的更新dict的方法,它使用__setitem__方法。下面是一个如何使用__setitem__方法向dict添加键值对的示例,以及使用它的糟糕性能的演示:
>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}
>>> def f():
... d = {}
... for i in xrange(100):
... d['foo'] = i
...
>>> def g():
... d = {}
... for i in xrange(100):
... d.__setitem__('foo', i)
...
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539
所以我们看到,使用下标符号实际上比使用__setitem__快得多。做Pythonic的事情,也就是说,按照预期的方式使用语言,通常既可读性更高,计算效率也更高。
其他回答
通过为字典中的键指定值,可以在字典中创建新的键/值对
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
如果键不存在,则添加该键并指向该值。如果它存在,它所指向的当前值将被覆盖。
我认为指出Python的集合模块也很有用,它由许多有用的字典子类和包装器组成,简化了字典中数据类型的添加和修改,特别是defaultdict:
调用工厂函数以提供缺失值的dict子类
如果您使用的字典总是由相同的数据类型或结构组成,例如列表字典,那么这尤其有用。
>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})
如果键还不存在,defaultdict会将给定的值(在我们的例子中为10)作为初始值分配给字典(通常在循环中使用)。因此,此操作执行两件事:它向字典中添加一个新键(根据问题),如果键还不存在,则分配值。对于标准字典,当+=操作试图访问一个尚不存在的值时,这可能会引发错误:
>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'key'
如果不使用defaultdict,添加新元素的代码量会更大,可能看起来像:
# This type of code would often be inside a loop
if 'key' not in example:
example['key'] = 0 # add key and initial value to dict; could also be a list
example['key'] += 1 # this is implementing a counter
defaultdict还可以用于复杂的数据类型,例如列表和集合:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
添加元素会自动初始化列表。
dico[“new key”]=“value”
在不使用add的情况下向字典中添加关键字
# Inserting/Updating single value
# subscript notation method
d['mynewkey'] = 'mynewvalue' # Updates if 'a' exists, else adds 'a'
# OR
d.update({'mynewkey': 'mynewvalue'})
# OR
d.update(dict('mynewkey'='mynewvalue'))
# OR
d.update('mynewkey'='mynewvalue')
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
# To add/update multiple keys simultaneously, use d.update():
x = {3:4, 5:6, 7:8}
d.update(x)
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue', 3: 4, 5: 6, 7: 8}
# update operator |= now works for dictionaries:
d |= {'c':3,'d':4}
# Assigning new key value pair using dictionary unpacking.
data1 = {4:6, 9:10, 17:20}
data2 = {20:30, 32:48, 90:100}
data3 = { 38:"value", 99:"notvalid"}
d = {**data1, **data2, **data3}
# The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
# Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))
如果您想在字典中添加字典,可以这样做。
示例:向字典和子字典添加新条目
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"] = {}
在添加条目之前。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象