On 03/25/2015 12:51 PM, Andrew Barnert wrote:
On Mar 25, 2015, at 04:00, Thomas Güttler
wrote:
I am missing OrderedDict.insert()
With what interface? Does it take an index, like list.insert, even though other OrderedDict methods (including __getitem__ and friends) don't? Or does it take another key? If so, does it insert before or after that key? And what if that key doesn't exist? Meanwhile, if the new key was already in the dict, should it move to the new position, update values in place, or raise an exception? Do you expect O(1) performance?
Other people, too:
http://stackoverflow.com/questions/16664874/how-can-i-add-the-element-at-the...
That other person is asking for some way to put a new element on the left instead of the right, which doesn't have any of those issues. (And which is already possible with move_to_end.) And an anonymous low-rep user asking a question, getting a handful of upvotes, and accepting an answer that says "You can't, just build a new dict" with no comment doesn't exactly show a burning desire within a wide community.
In fact, I think this does a better job showing how OrderedDict is often an attractive nuisance than how it's incomplete--the guy can't explain why he wants this, and meanwhile he apparently thinks you have to build a new dict and call update to add a value (or at least that doing so should have a different result than just using __setitem__ with that new key and value). My guess is that either he didn't really want an OrderedDict in the first place, or Zagorulkin Dmitri is right that the real problem is that his program needs this feature and it should be rewritten so it doesn't. But without actually knowing the use case that's just a guess.
As to OrderedDict being a an attractive nuisance, I'm not sure. I do think there are data structures that benefit from being index-able by both position and by name. Scheme uses association lists for this, and documents that they are a bit slower than mappings. But it is easy to convert one to the other and back again. In python you can convert to a list of items and back. But it can be expensive to keep two versions of the same data in memory or to constantly convert back and forth. An ordered dict insures the conversion to an items list will result in a dependable order. That may be the primary benefit. One way to do an insert is to mirror how the __init__ method works with items, but with an index for the first value. Dict.insert_items(index, items) Another possibility is to have both get_items and set_items methods than accept an index or slice object as the first argument. The __getitem__ and __setitem__ methods should not take an index in a dictionary. It is a dictionary first, and ordered data second. If it was an association list, then this would be reversed. Cheers, Ron