是否可以在创建Python字典后添加密钥?它似乎没有 .add()
方法。
是否可以在创建Python字典后添加密钥?它似乎没有 .add()
方法。
>>> d = {'key':'value'}
>>> print(d)
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print(d)
{'mynewkey': 'mynewvalue', 'key': 'value'}
>>> d = {'key':'value'}
>>> print(d)
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print(d)
{'mynewkey': 'mynewvalue', 'key': 'value'}
>>> x = {1:2}
>>> print x
{1: 2}
>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}
我想整合有关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'
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
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["key"] = "value"
“在创建Python字典之后是否可以添加密钥?它似乎没有.add()方法。”
是的,它是可能的,它确实有一个实现这个的方法,但你不想直接使用它。
为了演示如何以及如何不使用它,让我们用dict文字创建一个空的dict, {}
:
my_dict = {}
要使用单个新键和值更新此dict,您可以使用 下标符号(参见这里的映射) 提供项目分配:
my_dict['new key'] = 'new value'
my_dict
就是现在:
{'new key': 'new value'}
update
方法 - 2种方式我们还可以使用多个值有效地更新dict 该 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创建键,在这里我们当然避免创建额外的不必要的 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__
将键值对添加到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
所以我们看到使用下标符号实际上比使用快得多 __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__
方法是如何使自己的类支持方括号语法。看到 http://www.diveintopython.net/object_oriented_framework/special_class_methods.html
你可以创建一个
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' )
data = {}
data['a'] = 'A'
data['b'] = 'B'
for key, value in data.iteritems():
print "%s-%s" % (key, value)
结果是
a-A
b-B