Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Writing an empty dictionary with strings thats ordered

Please realize I'm trying not looking for a default ordered dictionary like this question. Something similar.

If I call an OrderedDict from the collections module I can do -

 from collections import OrderedDict
 my_ordered_dict = OrderedDict()

Then I can just set items like this which calls on the setitem function, where I assume the magic happens -

 my_ordered_dict[key1] = value1
 my_ordered_dict[key2] = value2
 my_ordered_dict[key3] = value3

And get a perfectly OrderedDict -

>my_ordered_dict
 {key1:value1, key2:value2, key3:value3...}

However, when I try to just initilize my key value pairing like this:

my_ordered_dict = {key1 : value1,
                   key2 : value2,
                   key3 : value3...}

The dictionary loses order.

I can hack my way around this by instead of initializing a list of tuples:

default = [ (key1, value1), (key2, value2), (key3, value3)]

for pair in default:
   my_ordered_dict[pair[0]] = pair[1]

But it seems like i'm missing something. Any tips?

like image 577
jwillis0720 Avatar asked Sep 16 '25 06:09

jwillis0720


1 Answers

This works:

my_ordered_dict = OrderedDict(( (key1, value1), (key2, value2), (key3, value3) ))

The above works because the argument we are using is tuple and a tuple is ordered.

Again because a tuple is ordered, this will also work :

my_ordered_dict = OrderedDict()
my_ordered_dict.update(( (key1, value1), (key2, value2), (key3, value3) ))

By contrast, this will not work:

my_ordered_dict = OrderedDict({key1:value1, key2:value2,})

The argument to OrderedDict above is an unordered dictionary. All order was lost when it was created.

Interestingly, though, order can be reimposed on an unordered dictionary as these examples from the documention for the collections module show:

>>> # 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)])
like image 139
John1024 Avatar answered Sep 19 '25 07:09

John1024