# dict在Python中的含义
# dict是Python内置的数据类型之一,表示字典。字典是由键值对组成的集合,每个键值对包含一个键和一个对应的值。
# 字典的键必须是不可变类型(如字符串、数字或元组),而值可以是任意类型。
# 示例代码:
# 创建一个空字典
empty_dict = {}
print(empty_dict) # 输出: {}
# 创建一个包含键值对的字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person) # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}
# 访问字典中的值
name = person["name"]
print(name) # 输出: Alice
# 添加新的键值对
person["email"] = "alice@example.com"
print(person) # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email': 'alice@example.com'}
# 修改现有键的值
person["age"] = 31
print(person) # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
# 删除键值对
del person["city"]
print(person) # 输出: {'name': 'Alice', 'age': 31, 'email': 'alice@example.com'}
# 检查键是否存在
if "name" in person:
print("Name is in the dictionary") # 输出: Name is in the dictionary
# 获取字典的所有键
keys = person.keys()
print(keys) # 输出: dict_keys(['name', 'age', 'email'])
# 获取字典的所有值
values = person.values()
print(values) # 输出: dict_values(['Alice', 31, 'alice@example.com'])
# 获取字典的所有键值对
items = person.items()
print(items) # 输出: dict_items([('name', 'Alice'), ('age', 31), ('email', 'alice@example.com')])
下一篇:python中yield
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站