一文讲清Python找到与字典相关的常用函数
创建字典
建立一个新字典:
# A tome of elements and their symbols
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'}
2. 添加或更新条目
添加新条目或更新现有条目:
elements['Carbon'] = 'C' # Adds 'Carbon' or updates its value to 'C'
3. 删除条目
将条目从字典中删除:
del elements['Lithium'] # Removes the key 'Lithium' and its value
4. 检查键是否存在
检查一个键是否位于字典中:
if 'Helium' in elements:
print('Helium is present')
5. 遍历键
遍历字典中的键:
for element in elements:
print(element) # Prints each key
6. 遍历值
遍历字典中的值:
for symbol in elements.values():
print(symbol) # Prints each value
7. 遍历项目
共同遍历键和值:
for element, symbol in elements.items():
print(f'{element}: {symbol}')
8. 字典推导
通过在可迭代对象上念咒语来召唤一个新的字典:
# Squares of numbers from 0 to 4
squares = {x: x**2 for x in range(5)}
9. 合并字典
合并两个或多个字典,形成它们条目的新联盟:
alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
merged = {**alchemists, **philosophers} # Python 3.5+
10. 使用默认值获取值
为了安全地检索一个值,为缺失的键提供默认值:
element = elements.get('Neon', 'Unknown') # Returns 'Unknown' if 'Neon' is not fo