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) # {'a', 'b', 'r', 'c', 'd'}

Example 2: python ordereddict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> 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")