【基础04】【自学笔记】python-字典和集合
一、字典
字典(英文名 dict),它是由一系列的键值(key-value)对组合而成的数据结构。
1. 创建字典
创建一个字典有三种方法
第一种方法:先使用 dict() 创建空字典实例,再往实例中添加元素
>>> profile = dict(name="王炳明", age=27, 众号="ython编程")
>>> profile
{'name': '王炳明', 'age': 27, '众号': 'ython编程'}
第二种方法:直接使用 {} 定义字典,并填充元素。
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> profile
{'name': '王炳明', 'age': 27, '公众号': 'Python编程'}
第三种方法:使用 dict() 构造函数可以直接从键值对序列里创建字典。
>>> info = [('name', '王炳明 '), ('age', 27), ('公众号', 'Python编程')]
>>> dict(info)
{'name': '王炳明 ', 'age': 27, '公众号': 'Python编程'}
第四种方法:使用字典推导式
>>> adict = {x: x**2 for x in (2, 4, 6)}
>>> adict
{2: 4, 4: 16, 6: 36}
2. 增删改查
增删改查:是 新增元素、删除元素、修改元素、查看元素的简写。
由于,内容比较简单,让我们直接看演示
查看元素
查看或者访问元素,直接使用 dict[key] 的方式就可以
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> profile["公众号"]
'Python编程'
但这种方法,在 key 不存在时会报 KeyValue 的异常
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> profile["gender"]
Traceback (most recent call last):
File "", line 1, in
KeyError: 'gender'
所以更好的查看获取值的方法是使用 get() 函数,当不存在 gender 的key时,默认返回 male
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> profile.get("gender", "male")
'male'
新增元素
新增元素,直接使用 dict[key] = value 就可以
>>> profile = dict()
>>> profile
{}
>>> profile["name"] = "王炳明"
>>> profile["age"] = 27
>>> profile["公众号"] = "Python编程"
>>> profile
{'name': '王炳明','age': 27,'公众号': 'Python编程'}
修改元素
修改元素,直接使用 dict[key] = new_value 就可以
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>>
>>> profile["age"] = 28
>>> profile
{'name': '王炳明', 'age': 28, '公众号': 'Python编程'}
删除元素
删除元素,有三种方法
第一种方法:使用 pop 函数
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> profile.pop("age")
27
>>> profile
{'name': '王炳明', '公众号': 'Python编程'}
第二种方法:使用 del 函数
>>> profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
>>> del profile["age"]
>>> profile
{'name': '王炳明', '公众号': 'Python编程'}
要给某个 key 设置默认值,最简单的方法
profile = {"name": "王炳明", "age": 27, "公众号": "Python编程"}
profile.setdefault("gender", "male")
二、集合
1. 创建集合
集合的创建有两种方法
第一种方法:使用 花括号 {} 直接创建,创建的时候,{} 可以包含有重要的元素,但是创建完后,集合会去重,只留第一个。
aset = {"Apple", "Huawei", "Xiaomi"}
print(type(aset))
print(aset)
结果:
{'Apple', 'Huawei', 'Xiaomi'}
第二种方法:使用 set() 方法进行创建,当set() 函数不接任何参数时,创建的是空集合,如果不创建空集合,可以传入一个列表。
bset=set() print(bset) print(type(bset)) bset=set(["Apple", "Huawei", "Xiaomi"]) print(bset)
结果:
set(){'Apple', 'Xiaomi', 'Huawei'}
记住:集合只有添加元素、删除元素。
使用 add 函数可以往集合中传入函数
>>> aset = set()
>>>
>>> aset
set([])
>>> aset.add("Apple")
>>> aset.add("Huawei")
>>> aset
set(['Huawei', 'Apple'])
删除元素
使用 remove 函数可以删除集合中的元素
>>> aset = {"Apple", "Huawei", "Xiaomi"}
>>> aset.remove("Xiaomi")
>>> aset
set(['Huawei', 'Apple'])
使用 remove 函数,如果对应的元素不存在,是会报错的。
>>> aset = {"Apple", "Huawei", "Xiaomi"}
>>> aset.remove("VIVO")
Traceback (most recent call last):
File "", line 1, in
KeyError: 'VIVO'
对于这种情况,你可以使用 discard 函数,存在元素则移除,不存在也不会报错。
>>> aset = {"Apple", "Huawei", "Xiaomi"}
>>> aset.discard("VIVO")
>>> aset
set(['Huawei', 'Xiaomi', 'Apple'])