遇到的Python字典操作难题实例
在Python中,处理字典的常见问题包括:
- 查找键或值:
```python
dict = {‘name’: ‘John’, ‘age’: 30}
根据键查找
value = dict.get(‘name’) # 如果键不存在,会返回None
print(value) # 输出:John
根据值查找键(多值问题)
keys = dict.keys() if ‘name’ in dict else []
for key in keys:
if dict[key] == ‘John’: # 假设我们想要的是所有名为John的值
print(key, “also has John as a value”)
2. 更新字典:
```python
dict = {'name': 'John', 'age': 30}
# 添加新的键值对
dict['job'] = 'Engineer'
print(dict) # 输出:{'name': 'John', 'age': 30, 'job': 'Engineer'}
# 更新已存在的键值对
dict['age'] = 40 # 更新年龄
print(dict) # 输出:{'name': 'John', 'age': 40, 'job': 'Engineer'}
这些例子展示了如何处理常见的字典操作问题。
还没有评论,来说两句吧...