是否可以在创建 Python 字典后为其添加键?
好像没有.add()
方法。
您通过为该键分配一个值来在字典上创建一个新的键/值对
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
如果键不存在,则添加并指向该值。如果存在,则覆盖它指向的当前值。
要同时添加多个键,请使用dict.update()
:
>>> 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}
对于添加单个密钥,接受的答案具有较少的计算开销。
我想整合有关 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'
更新运算符 现在|=
适用于字典:
data |= {'c':3,'d':4}
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
这使用了一个称为字典解包的新功能。
data = {**data1, **data2, **data3}
合并运算符 |
现在适用于字典:
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))
“是否可以在创建 Python 字典后为其添加键?它似乎没有 .add() 方法。”
是的,这是可能的,并且它确实有一个实现这一点的方法,但你不想直接使用它。
为了演示如何以及如何不使用它,让我们用 dict 文字创建一个空 dict {}
,:
my_dict = {}
要使用单个新键和值更新此 dict,您可以使用提供项目分配的下标表示法(请参阅此处的映射) :
my_dict['new key'] = 'new value'
my_dict
就是现在:
{'new key': 'new value'}
update
方法 - 2 种方式我们还可以使用方法有效地更新具有多个值的update
字典。我们可能在这里不必要地创建了一个额外的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
:
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'}
所以现在我们已经介绍了三种 Pythonic 更新dict
.
__setitem__
以及为什么应该避免它还有另一种更新dict
你不应该使用的方法,它使用该__setitem__
方法。这是一个如何使用该__setitem__
方法将键值对添加到 adict
的示例,并演示了使用它的性能不佳:
>>> 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 的事情,即按照预期的方式使用语言,通常更具可读性和计算效率。
dictionary[key] = value
如果你想在字典中添加字典,你可以这样做。
示例:向您的字典和子字典添加一个新条目
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,5.6。特殊类方法。
您可以创建一个:
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}
这个流行的问题解决了合并字典a
和b
.
以下是一些更直接的方法(在 Python 3 中测试)...
c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )
注意:上面的第一种方法只有在键b
是字符串的情况下才有效。
要添加或修改单个元素,b
字典将只包含那个元素...
c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
这相当于...
def functional_dict_add( dictionary, key, value ):
temp = dictionary.copy()
temp[key] = value
return temp
c = functional_dict_add( a, 'd', 'dog' )
假设您想生活在不可变的世界中,不想修改原始世界,但想要创建一个新的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}
和
new_params
等于{'a': 1, 'b': 2, 'c': 3}
有时您不想修改原始文件(您只想要添加到原始文件的结果)。我发现这是一个令人耳目一新的替代方案:
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
或者
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})
还有一个名字奇怪,行为古怪,但仍然很方便的东西dict.setdefault()
。
这
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
更新字典有两种方法:
使用方括号表示法 ( []
)
my_dict = {}
my_dict['key'] = 'value'
使用update()
方法
my_dict = {}
my_dict.update({'key': 'value'})
如果您没有加入两个字典,而是将新的键值对添加到字典中,那么使用下标表示法似乎是最好的方法。
import timeit
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383
但是,如果您想添加例如数千个新的键值对,您应该考虑使用该update()
方法。
这个问题已经得到了令人作呕的回答,但是由于我的 评论 获得了很大的关注,所以这里是一个答案:
如果您在这里试图弄清楚如何添加一个键并返回一个新字典(不修改现有字典),您可以使用以下技术做到这一点
new_dict = {**mydict, 'new_key': new_val}
new_dict = dict(mydict, new_key=new_val)
请注意,使用这种方法,您的密钥将需要遵循python中有效标识符名称的规则。
这是我在这里没有看到的另一种方式:
>>> 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}
>>>
以上是使用字典理解。
首先检查key是否已经存在:
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
然后您可以添加新的键和值。
您可以使用方括号:
my_dict = {}
my_dict["key"] = "value"
或者您可以使用.update()方法:
my_another_dict = {"key": "value"}
my_dict = {}
my_dict.update(my_another_dict)
这里有一个简单的方法!
your_dict = {}
your_dict['someKey'] = 'someValue'
这将key: value
在your_dict
字典中添加一对新的key = someKey
和value = somevalue
如果键的值somekey
已经存在于your_dict
.
your_dict = {}
添加新密钥:
your_dict[key]=value
your_dict.update(key=value)
dict 类中存在一个应该适合您的更新方法。
考虑:
# dictionary = {"key":"value"}
但是没有任何方法,您可以通过创建一个新值来添加一个键,如下所示:
dictionary['newkey'] = 'newvalue'
或使用更新https://www.python.org/dev/peps/pep-0584/#dict-update
dictionary.update({'newkey':'newvalue'})
我认为指出 Python 的collections
模块也很有用,该模块由许多有用的字典子类和包装器组成,它们简化了字典中数据类型的添加和修改,特别是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
也可以用于复杂的数据类型,例如list
和set
:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
添加元素会自动初始化列表。
添加一个字典(键,值)类。
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
#self[key] = value # add new key and value overwriting any exiting same key
if self.get(key)!=None:
print('key', key, 'already used') # report if key already used
self.setdefault(key, value) # if key exit do nothing
## example
myd = myDict()
name = "fred"
myd.add('apples',6)
print('\n', myd)
myd.add('bananas',3)
print('\n', myd)
myd.add('jack', 7)
print('\n', myd)
myd.add(name, myd)
print('\n', myd)
myd.add('apples', 23)
print('\n', myd)
myd.add(name, 2)
print(myd)
您可以像这样创建一个新的键值对:
my_dictionary = {"key1" : "value1"}
my_dictionary["key2"] = "value2"
要更改“key1”或“value2”,您可以执行相同的操作,如下所示:
my_dictionary = {"key1" : "value1"}
my_dictionary["key2"] = "value2"
my_dictionary["key1"] = "value1_revised"