I would like to combine OrderedDict()
and defaultdict()
from collections
in one object, which shall be an ordered, default dict. Is this possible?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Inspired by other answers on this thread, you can use something like,
I would like to know if there're any downsides of initializing another object of the same class in the missing method.
Here's another solution to think about if your use case is simple like mine and you don't necessarily want to add the complexity of a
DefaultOrderedDict
class implementation to your code.(
None
is my desired default value.)Note that this solution won't work if one of your requirements is to dynamically insert new keys with the default value. A tradeoff of simplicity.
Update 3/13/17 - I learned of a convenience function for this use case. Same as above but you can omit the line
items = ...
and just:Output:
And if your keys are single characters, you can just pass one string:
This has the same output as the two examples above.
You can also pass a default value as the second arg to
OrderedDict.fromkeys(...)
.Here is another possibility, inspired by Raymond Hettinger's super() Considered Super, tested on Python 2.7.X and 3.4.X:
If you check out the class's MRO (aka,
help(OrderedDefaultDict)
), you'll see this:meaning that when an instance of
OrderedDefaultDict
is initialized, it defers to theOrderedDict
's init, but this one in turn will call thedefaultdict
's methods before calling__builtin__.dict
, which is precisely what we want.i tested the default dict and discovered it's also sorted! maybe it was just a coincidence but anyway you can use the sorted function:
i think it's simpler
A simple and elegant solution building on @NickBread. Has a slightly different API to set the factory, but good defaults are always nice to have.
If you want a simple solution that doesn't require a class, you can just use
OrderedDict.setdefault(key, default=None)
orOrderedDict.get(key, default=None)
. If you only get / set from a few places, say in a loop, you can easily just setdefault.It is even easier for lists with
setdefault
:But if you use it more than a few times, it is probably better to set up a class, like in the other answers.