1、字典
Python字典是一种可变容器模型,可存储任意类型对象,如字符串、数字、元组等其他容器模型。 Python中字典的每个元素都包含两部分,键(key)值(value),键和值之间使用冒号(:)分隔,相邻元素使用逗号(,)分隔。所有元素放在大括号{}中。因为字典是无序的,所以不支持索引和切片。
格式:字典名={元素1, 元素2,...}
元素以键值对存在 = key(键值):value(实值)
注意:key不可以重复,否则只会保留第一个
value可以重复
key可以是任意的数据类型,但不能出现可变的数据类型,保证key唯一
key一般形式为字符串
1.1、创建字典
# 使用{}创建
dict_one = {"nane": "李长林", "sex": "男", "age": 26,}
print(dict_one)
# 空字典
dict_two={}
# 或
dict_three = dict()
print(dict_two)
print(dict_three)
# 通过fromkeys()方法创建字典
# 格式:dictname = dict.fromkeys(list, value = None)
listone = ['语文', '数学', '英语']
scores = dict.fromkeys(listone, 90)
print(scores)
# 输出 {'name':'李长林', 'sex':'男', 'age':26}
# 输出 {}
# 输出 {}
# 输出 {'语文':90, '数学':90, '英语':90}
注意:同一字典中的各个键必须唯一,不能重复。字典的键可以是整数、字符串、元组,只要符合唯一和不可变的特性就可以;字典的值可以是Python支持的任意数据类型
1.2、访问字典
1)、通过键访问: 字典和列表元组不同,不是通过下标访问元素; 字典是通过键来访问对应的值。因为字典中的元素是无序的,每个元素的位置不固定,所以字典也不能像列表和元组那样,采用切片的方式一次性访问多个元素。
格式:dictname[key]
dictname:字典变量的名字
key:键名
注意:键必须存在,否则会抛出异常,如下:
info = {'name':'李长林', 'sex':'男', 'age':26}
print(info['age'] # 键存在
# print(info['birth'] # 键不存在
# 输出 26
2)、通过get()方法访问:使用get()访问时,当指定的键不存在,get()不会抛出异常。
格式:dictname.get(key[,default])
dictname:表示字典变量的名字
key:表示指定的键
default:用于指定要查询的键不存在时,此方法返回的默认值,如果不手动指定,会返回None
dictname = (['语文', 90], ['数学', 85], ['英语', 95])
print(dictname.get('语文'))
print(dictname.get('化学','该键不存在'))
# 输出:
# 90
# 该键不存在
3)、通过setdefault获取
格式:dictname.setdefault(k, value)
用法:
- 如果key值存在,那么返回对应字典的value,不会用到自己设置的value;
- 如果key值不存在,且没设置value,返回None,并且把新设置的key和value保存到字典中
- 如果key值不存在,但设置了value,则返回设置的value
info = {'name':'李长林', 'sex':'男', 'age':26}
# 如果key值存在,返回对应的value
print(info.setdefault("name"))
print(info.setdefault("name", "可乐续命"))
print(info)
# 如果key值不存在,返回None, 设置的加入字典中
print(info.setdefault("name1"))
print(info)
'''
输出:
'李长林'
'李长林'
{'name':'李长林', 'sex':'男', 'age':26}
None
{'name':'李长林', 'sex':'男', 'age':26, 'name1':None}
'''
1.3、字典的增删查改
格式:
增:dictname[new key] = new value
删:del dictname[key]
查:value = dictname[key]
改:dictname[key] = new value
dictname = {'one':100, 'two':78, 'three':90, 'four':89}
# 增
dictname['five'] = 88
print(dictname)
# 删
del dictname['four']
print(dictname)
# 查
value = dictname['one']
print(value)
# 改
dictname['two'] = 22
print(dictname)
# 输出
# {'one':100, 'two':78, 'three':90, 'four':89, 'five':88}
# {'one':100, 'two':78, 'three':90, 'five':88}
# 100
# {'one':100, 'two':22, 'three':90, 'five':88}
1.4、字典的常见操作
方法 | 作用 |
len() |
获取字典中键值对的个数 |
keys() | 返回字典中所有的key |
values() | 返回包含value的列表 |
items() | 返回包含(键值,实值)元组的列表 |
in\not in | 判断key是否存在字典中 |
info = {'name':'李长林', 'sex':'男', 'age':26}
# len()
print(len(info))
# keys()
print(info.keys())
# values()
print(info.values())
# items()
print(info.items())
# in\not in
if 20 in info.values():
print("年龄")
if "可乐续命" not in info.values():
print("没有可乐续命")
# 输出:
# 3
# info_keys(['name', 'sex', 'age'])
# info_values(['李长林', '男', 26])
# info_items([('name', '李长林'), ('sex', '男'), ('age', 26)])
# 年龄
# 没有可乐续命
1.5、遍历字典
info = {'name':'李长林', 'sex':'男', 'age':26}
# 1、使用key遍历
for i in info.keys():
print(i) # 输出 name sex age
# 2、使用value遍历
for j in info.values()
print(i) # 输出 李长林 男 26
# 3、使用item遍历
for i in info.items():
print(i) # 输出 ('name', '李长林') ('sex','男') ('age', 26)
# 4、依次打印key和value
for key, value in info.items():
print(key, value) # 输出 (name, 李长林) (sex, 男) (age, 26)
# 5、元素值和对应的下标索引
for i in enumerate(info):
print(i) # 输出 (0, 'name') (1, 'sex') (2, 'age')
2、集合
集合(Set)是一种无序且不包含重复元素的数据结构,主要用来给数据去重。具有无序性、互异性、确定性。
2.1、创建集合
# 1、使用{}创建
myset = {1, 2, 3, 4, 5}
# 2、使用set函数创建集合
myset1 = set([1, 2, 3, 4, 3, 3, 5]) # 自动移除重复元素
# 3、创建空集合
empty_set = set()
2.2、集合的内置方法
1)、add():向集合末尾追加值
# 创建一个集合
myset = {1, 2, 3, 4, 5, 6, 7}
myset.add(10)
print(myset)
# 输出:{1, 2, 3, 4, 5, 6, 7, 10}
2)、update(): 更新整个集合
x = {'apple', 'banana', 'orange'}
y = {'fig', 'grape', 'apple'}
x.update(y)
print(x)
# 输出 {'apple', 'banana', 'fig', 'grape', 'orange'}
3)、 clear():移除集合中的所有元素
myset = {1,2,3}
myset.clear()
print(myset)
# 输出 set()
4)、copy():拷贝一个集合
set1 = {1, 2, 3}
set2 = set1.copy()
print(set2)
# 输出 {1, 2, 3}
5)、remove():移除指定元素
myset = {1, 2, 3, 4}
set1 = myset.remove(4)
print(set)
# 输出 {1, 2, 3}
6)、discard():删除指定元素
myset = {1, 2, 3, 4}
myset.discard(3)
print(myset)
# 输出 {1, 2, 4}