# Python字典用法示例
# 创建一个空字典
empty_dict = {}
# 或者使用 dict() 函数
empty_dict2 = dict()
# 创建一个带有键值对的字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 访问字典中的值
print(person["name"]) # 输出: Alice
# 或者使用 get 方法,如果键不存在则返回 None 或指定的默认值
print(person.get("age")) # 输出: 30
print(person.get("gender", "Unknown")) # 输出: Unknown
# 添加或修改字典中的键值对
person["email"] = "alice@example.com" # 添加新键值对
person["age"] = 31 # 修改现有键值对
# 删除字典中的键值对
del person["city"] # 删除键为 'city' 的键值对
# 或者使用 pop 方法,并可返回被删除的值
removed_value = person.pop("age") # 删除键为 'age' 的键值对并返回其值
# 获取所有键、值或键值对
keys = person.keys() # 获取所有键
values = person.values() # 获取所有值
items = person.items() # 获取所有键值对
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
# 检查键是否存在
if "name" in person:
print("Name is in the dictionary")
# 字典推导式
squares = {x: x*x for x in range(6)}
print(squares) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
上一篇:python代码如何运行
下一篇:python 运算符优先级
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站