Python|Python 字典
字典的特性:
? key - value 结构
? key 必须可 hash, 且必须为不可变数据类型, 必须唯一
? 可存放任意多个值, 可修改, 可以不唯一
? 无序, 所以字典无索引
? 查找快速
dic = {'susan':['女',28,'IT','alibaba']}
dic['susan']
>>> ['女', 28, 'IT', 'alibaba']
dic['susan'][0]
>>> '女'
字典的遍历:
dic2 = {'susan':'IT','ada':'singer','ak47':'gun'}
1. 遍历 key 值:
for k in dic2:
print(k,dic2[k])
>>> susan IT
ada singer
ak47 gunfor k in dic2.keys():
print(k,dic2[k])
>>> susan IT
ada singer
ak47 gun
【Python|Python 字典】在使用上, for k in dic2 与 for k in dic2.keys() 完全等价.
2. 遍历 value 值:
for v in dic2.values():
print(v)
>>> IT
singer
gun
3. 遍历字典项:
for k in dic2.items():
print(k)
>>> ('susan', 'IT')
('ada', 'singer')
('ak47', 'gun')
4. 遍历字典键值:
for k,v in dic2.items():
print(k,v)
>>> susan IT
ada singer
ak47 gun
修改字典:
1. 增加新的键值对:
dic3 = {}
dic3['name']='ada'
dic3
>>> {'name': 'ada'}
2. 修改键值对:
dic3['name']='xiaojiba'
dic3
>>> {'name': 'xiaojiba'}
删除字典:
dic4 = {'name':'xiaojiba','home':'beijing','job':'gamer'}
dic4
>>> {'name': 'xiaojiba', 'home': 'beijing', 'job': 'gamer'}
1. del 删除键值对
del dic4['home']
dic4
>>> {'name': 'xiaojiba', 'job': 'gamer'}
2. clear 清空字典
dic4.clear()
dic4
>>> {}
3. del 字典 ------> 字典被删除, dic4 然后会报错, 字典 not defined
del dic4
dic4
Traceback (most recent call last):
File "", line 1, in
NameError: name 'dic4' is not defined
字典 get 方法:
dic4 = {'name':'xiaojiba','home':'beijing','job':'gamer'}
dic4
>>> {'name': 'xiaojiba', 'home': 'beijing', 'job': 'gamer'}
dic4.get('name')
>>> 'xiaojiba'
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)
- 编写字典程序