一 、dict
- 字典是容器型数据类型,将{}作为容器的标志,里面多个元素(元素都是键值对) 用逗号隔开
{键1:值1,键2:值2,键3:值3,…}
注意:字典保存数据,其实是想要保存的是值,键的作用是对值进行区分和说明的。
字典可变(支持增删改);字典是无序的(不支持下标操作) - 字典的元素 -必须是键值对
键 - 必须是不可变的数据(一般使用字符串)、唯一的
值 - 任何类型的数据都可以,可以重复 - {} 是空字典
dict1 = {}
print(dict1, type(dict1))
dict2 = {10: 100, 12.5: 200, 'name': '张三', True: 300}
print(dict2)
dict3 = {(10, 20): 100}
- 列表是可变的数据不能作为key
关键字重复,自动删除前一个
dict4 = {10: 100, 20.5: 200, 10: 300}
print(dict4) # {10: 300, 20.5: 200}
dog = {‘name’: ‘little_dog’, ‘体重’: 32, ‘breed’: ‘藏獒’, ‘sex’: ‘boy’}
二、 字典的增删改查
1. 查 - 获取字典的值
a.字典[key] 相当于列表的下标 - 获取字典中指定key对应的值, key不存在就报错
film = {'name': '唐人街探案', 'director': '陈思成', 'time': 2018}
print(film['name'])
print(film['time'])
b.字典.get(key) --获取字典中指定key对应的值,不存在不报错返回None
print(film.get('name'))
print(film.get('time'))
c.字典.get(key,默认值)
key存在的话和前面两种方法没有区别,不存在的时候返回自己设置的默认值
print(film.get(‘age’, 0)) # 返回0
2. 遍历
- for -in 遍历字典的是,变量取到的是字典的键
students = [
{'name': 'stu1', 'age': 18, 'gender': '男', 'tel': '1101'},
{'name': 'stu2', 'age': 22, 'gender': '女', 'tel': '1104'},
{'name': 'stu3', 'age': 30, 'gender': '女', 'tel': '1105'},
{'name': 'stu4', 'age': 23, 'gender': '男', 'tel': '1106'},
{'name': 'stu5', 'age': 24, 'gender': '男', 'tel': '1108'},
{'name': 'stu6', 'age': 16, 'gender': '女', 'tel': '1109'}
]
sum1 = 0
count = 0
for x in students:
sum1 += x['age']
if x['gender'] == '女':
count += 1
print(round(sum1 / len(students), 2))
print(f'有{count}个女生')
#列表的推导式一句话实现
list1=[x['age'] for x in students]
print(sum(list1)/len(students))
list1=[x['gender'] for x in students ].count('女')
3.增、改
字典[key] = 值 -当key存在的时候就是改;不存在的时候就是增加
computer = {'price': 5432, 'brand': '联想'}
print(computer)
computer['color'] = '白色'
4. 删
- del 字典[key] -删除字典中指定key对应的键值对, 原则是先找再删,不存在就报错
computer = {'price': 5432, 'brand': '联想'}
del computer['price']
print(computer)
- 字典.pop(key) -取出字典中指定key对应的值
computer = {'price': 5432, 'brand': '联想'}
brand = computer.pop('brand')
print(computer, brand)
5. in 和 not in 操作
字典的in 和 not in 判断的某个key是否存在
dict1 = {'a': 10, 'b': 20, 'c': 30}
print(10 in dict1) # false
print('a' in dict1) # true
6.max、min、sum、sorted(了解) - 这些操作全部针对字典
7. dict(序列)-将序列转换成字典
序列的要求:a.序列钟的每个元素都是序列,
b.小序列有且只有两个元素
c.小序列的第一个元素不可变
seq = ['ab', '12', 'c1']
print(dict(seq))
seq1 = [range(2), ['name', '小明']]
print(dict(seq1))
8. 字典转列表,是将字典所有的键作为列表元素(所有序列都可以转换成列表)
dict2 = {'a': 10, 'b': 20, 'c': 30}
print(list(dict2)) # 存所有键
9.字典的相关函数
#key,values,items
student = {'name':'小明','age':18,'gender':'男'}
print(student.keys()) #dict_keys(['name', 'age', 'gender'])
print(student.values()) #dict_values(['小明', 18, '男'])
print(student.items()) #dict_items([('name', '小明'), ('age', 18), ('gender', '男')])