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))
我想整合有关Python字典的信息:
创建空字典
创建初始值
的字典插入/更新单个值
插入/更新多个值
在不修改原始词典的情况下创建合并词典
删除字典中的项目
检查字典中是否已存在密钥
在字典中遍历对
从两个列表中创建词典
Python3的新成员
在不修改原始词典的情况下创建合并词典
请随意添加更多!
要同时添加多个键,请使用^{} :
对于添加单个密钥,接受的答案具有较少的计算开销。
相关问题 更多 >
编程相关推荐