将新密钥添加到字典中?

是否可以在创建Python字典后添加一个键? 它似乎没有.add()方法。


>>> 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

从2个列表中创建一个字典

data = dict(zip(list_with_keys, list_with_values))

随意添加更多!

链接地址: http://www.djcxy.com/p/18143.html

上一篇: Add new keys to a dictionary?

下一篇: Finding anagrams for a given word