Python核心丨字典和集合

字典和集合


字典和集合基础

字典

字典是一系列由(key)和值(value)配对组成的元素的集合

在Python3.7+,字典被确定为有序

相比于列表和元组,字典的性能更优,特别是对于查找、添加和删除操作,字典都能在常数时间复杂度内完成。

集合

集合和字典基本相同,唯一的区别,集合没有键和值的配对,是一系列无序的、唯一的元素集合

  • 字典和集合的创建
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 = {123}
s2 = set([1, 2, 3])
s1 == s2
True
  • 字典元素访问
d = {'name': 'jason', 'age': 20}
d['name']
'jason'
d['location']
# 报错:KeyErrpr
  • 字典可以使用get(key, default)函数来进行索引
d = {'name': 'jason', 'age': 20}
d.get('name')
'jason'
d.get('location', 'none')
'none'

注:集合并不支持索引操作,因为集合本质上是一个哈希表,和列表不一样

s = {1, 2, 3}
s[0]
# 报错:TypeError
  • 想要判断一个元素在不在字典或集合内,可以使用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
  • 字典和集合支持增加、删除、更新等操作
d = {'name': 'jason', 'age': 20}
d['gender'] = 'male'  # 增加元素对'gender':'male'
d
{'name': 'jason', 'age': 20, 'gender': 'male'}
d['age'] = 30  # 更新键'age'对应的值
d.pop('gender')
d
{'name': 'jason', 'age': 30}

s = {1, 2, 3}
s.add(4)  # 增加元素4到集合
s
{1, 2, 3, 4}
s.remove(4)  # 从集合中删除元素4
s
{1, 2, 3}

注:集合的pop()操作时删除集合中最后一个元素,可是集合本身是无序的,不知道会删除哪个元素。

  • 根据字典的键或值,升序或降序
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]

#### 字典和集合性能

示例

  • 电商企业的后台,存储每件产品的ID、名称和加格。需求是,给定某件商品的ID,找出其价格
# 用列表来存储
def find_product_price(products, product_id):
    for id, price in products:
        if id == product_id:
            return price
    return None

products = [
    (143121312, 100),
    (432314553, 30),
    (32421912367, 150)
]

print('The price of product 432314553 is {}'.format(find_product_price(products, 432314553)))

# 输出结果:The price of product 432314553 is 30

假设列表有n个元素,而查找的过程要遍历列表,那么时间复杂度就为O(n)

如果用字典来存储数据,只需O(1)的时间复杂度就可以完成。

products = {
    143121312: 100,
    432314553: 30,
    32421912367: 150,
}
print('The price of product 432314553 is {}'.format(products[432314553]))

# 输出结果:The price of product 432314553 is 30
字典和集合的工作原理

字典和集合的内部结构都是一张哈希表

  • 对于字典而言,这张表存储了哈希值(hash)、键和值这3个元素

  • 对集合来说,区别就是哈希表内没有键和值的配对,只有单一的元素

'''
现在的哈希表除了字典本身的结构,
会把索引和哈希值、键、值单独分开。
'''
Indices
----------------------------------------------------
None | index | None | None | index | None | index ...
----------------------------------------------------

Entries
--------------------
hash0   key0  value0
---------------------
hash1   key1  value1
---------------------
hash2   key2  value2
---------------------
        ...
---------------------

示例中在新的哈希表结构下的存储形式


indices = [None, 1, None, None, 0, None, 2]
entries = [
[1231236123, 'name', 'mike'],
[-230273521, 'dob', '1999-01-01'],
[9371539127, 'gender', 'male']
]
插入操作

每次向字典和集合插入一个元素时,Python会首先计算键的哈希值(hash(key)),如果哈希表中此位置是空的,那么这个元素就会被插入其中。

如果此位置被占用,Python便会比较两个元素的哈希值和键是否相等。

  • 若两者都相等,则表明这个元素已经存在,如果值不同,则更新值
  • 若两者中有一个不相等,通常称为哈希冲突,意思是两个元素的键不相等,但是哈希值相等
查找操作

和插入操作类似,Python会根据哈希值,找到其应该处于的位置,然后,比较哈希表这个位置元素的哈希值和键,与需要查找的元素是否相等。

如果相等,则直接返回;如果不相等,则继续查找,直到找到空位或者抛出异常为止。

删除操作

对于删除操作,Python会暂时对这个位置的元素,赋予一个特殊的值,等到重新调整哈希表大小时,再将其删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值