访问 python 字典中元素的几种方式
一: 通过 "键值对"(key-value)访问:
- print(dict[key])
- dict = {
- 1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45
- }
- print(dict['D'])
输出:
ee
dict.get(key,[default]) :default 为可选项, 用于指定当'键'不存在时 返回一个默认值, 如果省略, 默认返回 None
- dict = {
- 1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45
- }
- print(dict.get(2))
- print(dict.get(3))
- print(dict.get(4, ['字典中不存在键为 4 的元素']))
输出:
- aa
- None
- ['字典中不存在键为 4 的元素']
二: 遍历字典:
1. 使用字典对象的 dict.items()方法获取字典的各个元素即 "键值对" 的元祖列表:
- dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
- for item in dict.items():
- print(item)
输出:
- (1, 1)
- (2, 'aa')
- ('D', 'ee')
- ('Ty', 45)
2. 获取到具体的每个键和值:
- dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
- for key, value in dict.items():
- print(key, value)
输出:
- 1 1
- 2 aa
- D ee
- Ty 45
3. 还可以使用 keys()和 values()方法获取字典的键和值列表:
- dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
- for key in dict.keys():
- print(key)
- for value in dict.values():
- print(value)
输出:
- 1
- 2
- D
- Ty
- 1
- aa
- ee
- 45
来源: http://www.bubuko.com/infodetail-3101930.html