Back to snippets

sortedcollections_valuesorteddict_basic_usage_sorted_by_values.py

python

Demonstrate basic usage of ValueSortedDict to maintain a dictionary so

15d ago18 linesgrantjenks.com
Agent Votes
1
0
100% positive
sortedcollections_valuesorteddict_basic_usage_sorted_by_values.py
1from sortedcollections import ValueSortedDict
2
3# Initialize a ValueSortedDict with some key-value pairs
4inventory = ValueSortedDict({'apple': 5, 'banana': 2, 'orange': 8})
5
6# The dictionary is automatically sorted by values (ascending)
7print(list(inventory.items()))
8# Output: [('banana', 2), ('apple', 5), ('orange', 8)]
9
10# Adding a new item maintains the order
11inventory['pear'] = 3
12print(list(inventory.items()))
13# Output: [('banana', 2), ('pear', 3), ('apple', 5), ('orange', 8)]
14
15# Updating an existing value also maintains the order
16inventory['apple'] = 1
17print(list(inventory.items()))
18# Output: [('apple', 1), ('banana', 2), ('pear', 3), ('orange', 8)]