Pao*_*ino 3189
d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
Run Code Online (Sandbox Code Playgroud)
        小智 990
>>> 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}
Run Code Online (Sandbox Code Playgroud)
        Yug*_*dle 852
我想整合有关Python字典的信息:
data = {}
# OR
data = dict()
Run Code Online (Sandbox Code Playgroud)
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))}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'
Run Code Online (Sandbox Code Playgroud)
data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2
Run Code Online (Sandbox Code Playgroud)
del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary
Run Code Online (Sandbox Code Playgroud)
key in data
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
data = dict(zip(list_with_keys, list_with_values))
Run Code Online (Sandbox Code Playgroud)
随意添加更多!
Aar*_*all 134
"在创建Python字典后,是否可以将其添加到Python字典中?它似乎没有.add()方法."
是的,它是可能的,它确实有一个实现这个的方法,但你不想直接使用它.
为了演示如何以及如何不使用它,让我们用dict文字创建一个空的dict {}:
my_dict = {}
Run Code Online (Sandbox Code Playgroud)
要使用单个新键和值更新此dict,可以使用提供项目分配的下标表示法(请参阅此处的映射):
my_dict['new key'] = 'new value'
Run Code Online (Sandbox Code Playgroud)
my_dict 就是现在:
{'new key': 'new value'}
Run Code Online (Sandbox Code Playgroud)
update方法 -  2种方法我们还可以使用该update方法有效地更新具有多个值的dict .我们可能会dict在这里不必要地创建一个额外的,所以我们希望我们dict已经创建并来自或用于其他目的:
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
Run Code Online (Sandbox Code Playgroud)
my_dict 就是现在:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
Run Code Online (Sandbox Code Playgroud)
使用update方法执行此操作的另一种有效方法是使用关键字参数,但由于它们必须是合法的python单词,因此您不能使用空格或特殊符号或使用数字开始名称,但许多人认为这是一种更易读的方式为dict创建密钥,在这里我们当然避免创建一个额外的不必要的dict:
my_dict.update(foo='bar', foo2='baz')
Run Code Online (Sandbox Code Playgroud)
而my_dict现在是:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}
Run Code Online (Sandbox Code Playgroud)
所以现在我们已经介绍了三种更新的Pythonic方法dict.
__setitem__以及为什么要避免它还有另一种更新dict不应使用的__setitem__方法,即使用该方法.下面是一个示例,说明如何使用该__setitem__方法向a添加键值对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
Run Code Online (Sandbox Code Playgroud)
所以我们看到使用下标符号实际上比使用快得多__setitem__.做Pythonic的事情,就是按照预期使用的方式使用语言,通常更具可读性和计算效率.
Ash*_*her 52
如果要在字典中添加字典,可以这样做.
示例:向字典和子字典中添加新条目
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)
Run Code Online (Sandbox Code Playgroud)
输出:
{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
Run Code Online (Sandbox Code Playgroud)
注意: Python要求您首先添加子
dictionary["dictionary_within_a_dictionary"] = {}
Run Code Online (Sandbox Code Playgroud)
在添加条目之前.
Col*_*nic 39
正统的语法是d[key] = value,但如果您的键盘缺少方括号键,您可以这样做:
d.__setitem__(key, value)
Run Code Online (Sandbox Code Playgroud)
实际上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法.见http://www.diveintopython.net/object_oriented_framework/special_class_methods.html
kir*_*off 33
你可以创建一个
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)
Run Code Online (Sandbox Code Playgroud)
给
>>> 
{'apples': 6, 'bananas': 3}
Run Code Online (Sandbox Code Playgroud)
        nob*_*bar 31
这种流行的问题解决功能合并字典的方法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() )
Run Code Online (Sandbox Code Playgroud)
注意:上面的第一种方法仅在键b是字符串时才有效.
要添加或修改单个元素,b字典只包含一个元素......
c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
Run Code Online (Sandbox Code Playgroud)
这相当于......
def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp
c = functional_dict_add( a, 'd', 'dog' )
Run Code Online (Sandbox Code Playgroud)
        cs9*_*s95 23
这个问题已经得到了令人作呕的回答,但由于我的(现已删除) 评论 获得了很大的关注,这里是一个答案:
如果您在这里试图弄清楚如何添加键并返回一个新字典(而不修改现有字典),您可以使用以下技术来完成此操作
new_dict = {**mydict, 'new_key': new_val}
Run Code Online (Sandbox Code Playgroud)
new_dict = dict(mydict, new_key=new_val)
Run Code Online (Sandbox Code Playgroud)
请注意,使用这种方法,您的密钥将需要遵循Python 中有效标识符名称的规则。
cam*_*son 20
让我们假装您想要生活在不可变的世界中,并且不想修改原始文件但想要创建一个新的dict,这是在原始文件中添加新密钥的结果.
在Python 3.5+中,您可以:
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
Run Code Online (Sandbox Code Playgroud)
Python 2的等价物是:
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
Run Code Online (Sandbox Code Playgroud)
在以下任何一个之后:
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
Run Code Online (Sandbox Code Playgroud)
要么
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})
Run Code Online (Sandbox Code Playgroud)
参考:https://stackoverflow.com/a/2255892/514866
Mic*_*oka 14
如此多的答案,仍然每个人都忘记了奇怪的名字,奇怪的表现,但仍然很方便 dict.setdefault()
这个
value = my_dict.setdefault(key, default)
Run Code Online (Sandbox Code Playgroud)
基本上这样做:
try:
    value = my_dict[key]
except KeyError: # key not found
    value = my_dict[key] = default
Run Code Online (Sandbox Code Playgroud)
例如
>>> 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
Run Code Online (Sandbox Code Playgroud)
        首先检查key是否已经存在:
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
Run Code Online (Sandbox Code Playgroud)
然后您可以添加新的键和值。
如果您不是连接两个字典,而是将新的键值对添加到字典中,那么使用下标表示法似乎是最好的方法。
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
Run Code Online (Sandbox Code Playgroud)
但是,例如,如果您想添加数千个新的键值对,则应考虑使用该update()方法。
添加字典(键,值)类。
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)
Run Code Online (Sandbox Code Playgroud)
        我认为指出 Python 的collections模块也很有用,该模块由许多有用的字典子类和包装器组成,它们简化了字典中数据类型的添加和修改,特别是defaultdict:
调用工厂函数来提供缺失值的 dict 子类
如果您使用的字典始终包含相同的数据类型或结构(例如列表字典),这尤其有用。
>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})
Run Code Online (Sandbox Code Playgroud)
如果键尚不存在,defaultdict则将给定的值(在我们的例子中10)作为初始值分配给字典(通常在循环内使用)。因此,此操作执行两件事:将新键添加到字典中(根据问题),并在该键尚不存在时分配该值。使用标准字典,这会引发错误,因为+=操作试图访问尚不存在的值:
>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key'
Run Code Online (Sandbox Code Playgroud)
如果不使用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
Run Code Online (Sandbox Code Playgroud)
defaultdict也可以与复杂的数据类型一起使用,例如list和set:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
Run Code Online (Sandbox Code Playgroud)
添加元素会自动初始化列表。
这是我在这里没有看到的另一种方式:
>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
您可以使用字典构造函数和隐式扩展来重建字典。此外,有趣的是,此方法可用于控制字典构建期间的位置顺序(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}
>>> 
Run Code Online (Sandbox Code Playgroud)
以上是使用字典理解。
        # 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))
Run Code Online (Sandbox Code Playgroud)