Is it possible to initialize an empty OrderedDict in Python with a predefined sorting mechanism? -



Is it possible to initialize an empty OrderedDict in Python with a predefined sorting mechanism? -

all examples find (in documentation, etc.) define ordereddicts passing info constructor. docs:

# regular unsorted dictionary d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted key ordereddict(sorted(d.items(), key=lambda t: t[0])) ordereddict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

on other hand, possible initialize ordereddict providing no parameters constructor, leads preserve order in key,value pairs added.

i looking kind of build resembles following, except without "d.items()". essentially, i'm asking remember mechanism without providing example, might sound crazy. alternative "hack" providing initial "d" (below) single item, or there improve way?

ordereddict(sorted(d.items(), key=lambda t: t[0]))

thank you!

ordereddict has 1 sorting algorithm: insertion order. whatever order items added ordereddict order ordereddict has.

if want other method can either write dict subclass or sort function can apply when order important.

python python-2.7 python-3.x ordereddictionary

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -