python3中的SortedDict用法

5 阅读1分钟

SortedDictsortedcontainers库中的一种数据结构,提供一个有序的字典,类似C++中的map。与python内置的dict不同,SortedDict保持键的顺序,因此可以根据键的顺序高效地访问元素。

安装sortedcontainers

pip install sortedcontainers

导入和创建SortedDict

from sortedcontainers import SortedDict

sd = SortedDict()
initial_dict = {'banana': 3, 'apple': 2, 'cherry': 5}
sd = SortedDict(initial_dict) #可以从一个已有的字典创建

添加元素,

sd["data"] = 4
sd["apple"] = 1 #更新已有键的值
print(sd)
#输出: SortedDict({'apple': 1, 'banana': 3, 'cherry': 5, 'date': 4})

访问元素,

print(sd['banana']) # 输出: 3

删除元素,

del sd['cherry'] 
print(sd) 
# 输出: SortedDict({'apple': 1, 'banana': 3, 'date': 4})

迭代,SortedDict按照键的排列顺序进行迭代,

for key in sd:
    print(key, sd[key])
# 输出:
# apple 1
# banana 3
# date 4

使用popitem方法。popitem方法可以按照顺序(默认从最后)移除并返回一个(key,val)对。

key, value = sd.popitem()
print(key, value)
# 输出: date 4

# 也可以使用 popitem(0) 从开头移除
key, value = sd.popitem(0)
print(key, value)
# 输出: apple 1

使用peekitem方法。peekitem方法可以查看特定位置的键值对。

from sortedcontainers import SortedDict

sd = SortedDict({'banana': 3, 'apple': 2, 'cherry': 5})
print(sd)
#输出 'apple': 2
#'banana': 3
#'cherry': 5
last_item = sd.peekitem() #默认最后一个元素
first_item = sd.peekitem(0) #查看下标为0的元素
second_item = sd.peekitem(1) #查看下标为1的元素 

获取键和值的范围。SortedDict提供了keys()values()方法,按排列顺序返回所有键和值。

keys = sd.keys()
values = sd.values()
print(list(keys))   # 输出: ['apple', 'banana', 'cherry']
print(list(values)) # 输出: [1, 3, 5]