python ordered set code example
Example 1: orderd set in python
pip install ordered-set
from ordered_set import OrderedSet
letters = OrderedSet('abracadabra')
print(letters)
Example 2: python ordereddict
>>>
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Example 3: are sets ordered in python
try:
a = {'a', 'b'}
print(a[0])
except:
print("Set are not ordered")