Ordered set python code example
Example 1: ordered dictionary python
from collections import OrderedDict
x = OrderedDict(a=1, b=2, c=3)
Example 2: orderd set in python
pip install ordered-set
from ordered_set import OrderedSet
letters = OrderedSet('abracadabra')
print(letters)
Example 3: 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 4: are sets ordered in python
try:
a = {'a', 'b'}
print(a[0])
except:
print("Set are not ordered")