相比于列表和元组,字典的性能更优,特别是对于查找、添加和删除操作,字典都能在常数时间复杂度内完成。
而集合和字典基本相同,唯一的区别,就是集合没有键和值的配对,是一系列无序的、唯一的元素组合。
1.字典和集合的创建
d1 = {'name': 'jason', 'age': 20, 'gender': 'male'}
d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
d4 = dict(name='jason', age=20, gender='male')
d1 == d2 == d3 ==d4
True
s1 = {1, 2, 3}
s2 = set([1, 2, 3])
s1 == s2
True
2.Python 中字典和集合,无论是键还是值,都可以是混合类型
3.字典的元素访问
字典访问可以直接索引键,如果不存在,就会抛出异常:
d = {'name': 'jason', 'age': 20}
d['name']
'jason'
d['location']
Traceback (most recent call last):
File "", line 1, in
KeyError: 'location'
也可以使用 get(key, default) 函数来进行索引。如果键不存在,调用 get() 函数可以返回一个默认值。比如下面这个示例,返回了'null'
d = {'name': 'jason', 'age': 20}
d.get('name')
'jason'
d.get('location', 'null')#可以自行设置默认值
'null'
4.集合的访问
集合并不支持索引操作,因为集合本质上是一个哈希表,和列表不一样。所以,下面这样的操作是错误的,Python 会抛出异常:
s = {1, 2, 3}
s[0]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'set' object does not support indexing
5.判断一个元素在不在字典或集合内,我们可以用 value in dict/set 来判断
s = {1, 2, 3}
1 in s
True
10 in s
False
d = {'name': 'jason', 'age': 20}
'name' in d
True
'location' in d
False
6.除创建和访问,字典和集合也同样支持增加、删除、更新等操作
集合的 pop() 操作是删除集合中最后一个元素,可是集合本身是无序的,无法知道会删除哪个元素,因此这个操作得谨慎使用!❗️❗️
7.对字典或集合进行排序
对字典的排序:
d = {'b': 1, 'a': 2, 'c': 10}
d_sorted_by_key = sorted(d.items(), key=lambda x: x[0]) # 根据字典键的升序排序
d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 根据字典值的升序排序
d_sorted_by_key
[('a', 2), ('b', 1), ('c', 10)]
d_sorted_by_value
[('b', 1), ('a', 2), ('c', 10)]
对集合排序
#直接调用 sorted(set) 即可,结果会返回一个排好序的列表
s = {3, 4, 2, 1}
sorted(s) # 对集合的元素进行升序排序
[1, 2, 3, 4]
8.字典和集合性能
字典和集合是进行过性能高度优化的数据结构,特别是对于查找、添加和删除操作