在Python中,字典(dict)通过键(key)来索引取值,而不是通过数字索引。以下是常见的操作方法及注意事项:
python
d = {'name': 'Alice', 'age': 25}
print(d['name']) 输出:Alice
python
print(d.get('address')) 输出:None
print(d.get('address', 'N/A')) 输出:N/A
逐层通过键访问:
python
nested_dict = {'person': {'name': 'Bob', 'age': 30}}
print(nested_dict['person']['name']) 输出:Bob
python
if 'address' in d:
print(d['address'])
else:
print('Key not found')
python
print(d.get('address', '默认值'))
虽然Python 3.7+的字典保留插入顺序,但依赖顺序访问可能影响代码可读性。若需按位置访问:
python
keys = list(d.keys)
first_key = keys[0]
print(d[first_key]) 输出第一个插入的键对应的值
python
基本用法
student = {'name': 'John', 'age': 22, 'courses': ['Math', 'Physics']}
print(student['age']) 22
print(student.get('phone', 'N/A')) N/A
嵌套字典
data = {'class': {'students': {'name': 'Alice'}}}
print(data['class']['students']['name']) Alice
处理键不存在
key = 'email'
value = student.get(key, '未提供')
print(f"{key}: {value}") email: 未提供
使用`get`或检查键是否存在来增强代码健壮性。
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态