2

I've read that OrderedDict can be used to keep information in a dictionary in order, but it seems to require that you input the information while instantiating the dictionary itself.

However, I need to be able to use update() multiple times in a for loop and ensure the each entry gets added to the end of the dictionary. Is there a way to do that?

Here's a visual of what I'm talking about

for e in entryList:
    myDict.update({e[2]: e[3]})

This enters all the new info, but doesn't keep it in order.

Community
  • 1
  • 1
Bob
  • 715
  • 2
  • 11
  • 32
  • `append()` for OrderedDict? Are you sure there is one? – Pavel Gurkov Sep 24 '16 at 23:19
  • So I suggest just go with the recommendations from this post again: http://stackoverflow.com/questions/13239279/is-it-possible-to-add-key-value-pair-at-the-end-of-the-dictionary-in-python – Erba Aitbayev Sep 24 '16 at 23:23

2 Answers2

3

Per the docs (https://docs.python.org/2/library/collections.html#collections.OrderedDict) you'll have to delete the entry before adding it.

You can wrap this in a subclass for convenience..:

class MyOrderedDict(OrderedDict):
    def update(self, other):
        for k, v in other.items():
            if k in self:
                 del self[k]
            self[k] = v

it seems strange to use update the way you do though:

myDict.update({e[2]: e[3]})

since it would be more clear to write:

myDict[e[2]] = e[3]

to make that work you'll also need to override __setitem__

class MyOrderedDict(OrderedDict):
    def __setitem__(self, key, val):
        if key in self:
             del self[key]
        super(self, MyOrderedDict).__setitem__(key, val)

    def update(self, other):
        for k, v in other.items():
            self[k] = v
thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

@Bob, please refer to the docs here. https://docs.python.org/3.5/library/collections.html?highlight=ordereddict#collections.OrderedDict

It says:

The OrderedDict constructor and update() method both accept keyword arguments, but their order is lost because Python’s function call semantics pass in keyword arguments using a regular unordered dictionary.

However, there's a workaround added in 3.2: (from the same page)

move_to_end(key, last=True) Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist.

I hope that answers the question.

Pavel Gurkov
  • 737
  • 5
  • 14