Bob Bob - 2 months ago 11
Python Question

How to ensure update() adds to end of dictionary

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.

Answer

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
Comments