# Python中处理键值对(key-value)最常用的数据结构是字典(dictionary)。以下是一个简单的示例代码,展示如何创建、访问和修改字典中的键值对。
# 创建一个字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 访问字典中的值
print(person["name"]) # 输出: Alice
# 修改字典中的值
person["age"] = 31
print(person["age"]) # 输出: 31
# 添加新的键值对
person["email"] = "alice@example.com"
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'}
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 31
# email: alice@example.com
下一篇:python 字符串比较大小
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站