python字典的基本操作列子

2023-11-19 19:45:25

以下是Python字典的基本操作示例:

1. 创建字典:

# 使用大括号创建字典
person = {'name': 'John', 'age': 25, 'city': 'Shang Hai'}

# 使用dict()函数创建字典
person = dict(name='John', age=25, city='Shang Hai')

2. 访问字典中的值:

# 使用键访问值
print(person['name'])  # 输出: John

# 使用get()方法访问值
print(person.get('age'))  # 输出: 25

3. 更新字典中的值:

person['age'] = 26  # 更新年龄为26
person['city'] = 'San Francisco'  # 更新城市为San Francisco

print(person)  # 输出: {'name': 'John', 'age': 26, 'city': 'San Francisco'}

4. 添加新的键值对:

person['occupation'] = 'Engineer'  # 添加职业为Engineer

print(person)  # 输出: {'name': 'John', 'age': 26, 'city': 'San Francisco', 'occupation': 'Engineer'}

5. 删除键值对:

del person['city']  # 删除键为'city'的键值对

print(person)  # 输出: {'name': 'John', 'age': 26, 'occupation': 'Engineer'}

6. 遍历字典:

# 遍历键
for key in person:
    print(key)

# 遍历值
for value in person.values():
    print(value)

# 遍历键值对
for key, value in person.items():
    print(key, value)

这些是Python字典的基本操作示例,希望对你有帮助!