python基础学习08——字典进阶
学习很辛苦,但并不痛苦!路漫漫其修远兮,吾将上下而求索!
1. 字典的定义
- 字典的生成
- 字面量方法
dict1 = {'a':1,'b':2,'c':2}
2. 构造器方法
dict1=dict(id='20181703034',name='yuping',age=23,brithday='11-09')
- 生成式方法
dict2={i:i*2 for i in range(10)}
list1=[(1,2),(3,4),(5,6)]
dict3={i[0]:i[0] for i in list1}
- 列表的生成式方法
list1 = [i for i in range(10)]
import random
list2=[random.randrange(10,100) for _ in range(10)]
- 集合的生成式方法
set1={i for i in range(10)}
print(set1,type(set1))
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} <class 'set'>
4.生成器方法
# 生成器
gen_obj = (i for i in range(1, 10))
print(next(gen_obj))
print(next(gen_obj))
print(next(gen_obj))
# 遍历
for i in gen_obj:
print(i)
2. 字典的遍历
- 通过键遍历
dict2={i:i*2 for i in range(10)}
for k in dict2 :
print(dict2[k])
# 方法二
for k in dict1.keys():
print(dict1[k])
- 通过值遍历
dict2={i:i*2 for i in range(10)}
for v in dict2.values :
print(v)
- 通过键值对遍历
dict2={i:i*2 for i in range(10)}
for k,v in dict2.items():
print(k,v)
3. 字典的操作
- 添加元素
student = dict(id='2103208', name='tian', sex=True, brithday='11-9')
# 字典的索引放在赋值运算符的左边
# 如果存在对于的键,修改原来的值,否则添加新的键值对,相当于student.update()方法
student['id'] = '20181703034' # 修改原来的值
student['address'] = '贵州镇远' # 添加新的键值对
print(student)
- 删除元素
# 删除键值对
print(student.pop('id')) # 返回被删除的值
# del student['salary'] # KeyError: 'salary',必须保证键存在
del student['sex']
print(student)
- 判断元素是否存在
dict2={i:i*2 for i in range(1,10)}
print(dict2)
# 通过键来确定元素是否存在
print(2 in dict2) # True
print(5 in dict2) # True
- 获取元素
dict1 = {'a':1,'b':2,'c':3}
print(dict['a']) # 当键不存在时会报,KeyError:
print(dict1.get('a')) # 返回对应的值,但不存在的时候默认返回None。也可以指定放回指
- 更新元素
dict1 = {'a':1,'b':2,'c':3}
dict1 = {'a':1,'b':2,'c':3}
dict1.update(a=23) # 存在就修改
dict1.update(d=34) # 不存在就添加
print(dict1) # {'a': 23, 'b': 2, 'c': 3, 'd': 34}
zip()函数的使用
- 实现字典的键和值的交换
dict1={'a': 23, 'b': 2, 'c': 3, 'd': 34}
dict1=dict(zip(dict1.values(),dict1.keys()))
print(dict1) # {23: 'a', 2: 'b', 3: 'c', 34: 'd'}
4. 字典的应用
4.1 网络数据采集———JSON数据
-
JSON:JavaScript Object Notation —>javaScript 对象表示法—>数据网站和数据接口使用的数据格式
-
通过天行数据API接口,获取JSON数据
- 垃圾分类提示程序
import requests word=input('输入你要分类的关键词:') # 获取请求,得到服务器的响应 resp=requests.get( url='http://api.tianapi.com/txapi/lajifenlei/index', params={'key':'0e2d040891cd207acfbf3da2cda513ba','word':word} ) # 通过json转换为字典,获取字典中需要数据的键 new_list=resp.json()['newslist'] # 遍历打印结构 for new in new_list: print(f"物品:{new['name']}") print(f"解释:\n{new['explain']}") print(f"放入方式:\n{new['contain']}") print(f"提示:\n{new['tip']}")
- 抽取判断题,键盘输入回答
import requests for _ in range(10): resp = requests.get( url='http://api.tianapi.com/txapi/decide/index', params={'key': '*'} # '*'申请的key ) new_list = resp.json()['newslist'] for choice in new_list: print(choice['title']) user_ch = int(input('请选择答案(1:正确 /0:错误):')) if user_ch == int(choice['answer']): print('你回答正确!') else: print('回答错误!') print(choice['analyse'],end=) print()
总结
字典数据类型在以后的编程中常常用来存储数据的首选,在数据分析中常常通过字典先封装数据在写入到对应的结构化数据文件、数据库的保存数据。