I would like to combine OrderedDict()
and defaultdict()
from collections
in one object, which shall be an ordered, default dict. Is this possible?
我想将OrderedDict()和defaultdict()从集合中合并到一个对象中,该对象应该是一个有序的默认命令。
7 个解决方案
#1
71
The following (using a modified version of this recipe) works for me:
下面(使用这个食谱的修改版本)为我工作:
from collections import OrderedDict, Callable
class DefaultOrderedDict(OrderedDict):
# Source: http://*.com/a/6190500/562769
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not isinstance(default_factory, Callable)):
raise TypeError('first argument must be callable')
OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
OrderedDict.__repr__(self))
#2
33
Here is another possibility, inspired by Raymond Hettinger's super() Considered Super, tested on Python 2.7.X and 3.4.X:
这是另一种可能,灵感来自Raymond Hettinger的super(),被认为是super,在Python 2.7上测试过。X和3.4.X:
from collections import OrderedDict, defaultdict
class OrderedDefaultDict(OrderedDict, defaultdict):
def __init__(self, default_factory=None, *args, **kwargs):
#in python3 you can omit the args to super
super(OrderedDefaultDict, self).__init__(*args, **kwargs)
self.default_factory = default_factory
If you check out the class's MRO (aka, help(OrderedDefaultDict)
), you'll see this:
如果您查看类的MRO (aka, help(OrderedDefaultDict de)),您将看到以下内容:
class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict)
| Method resolution order:
| OrderedDefaultDict
| collections.OrderedDict
| collections.defaultdict
| __builtin__.dict
| __builtin__.object
meaning that when an instance of OrderedDefaultDict
is initialized, it defers to the OrderedDict
's init, but this one in turn will call the defaultdict
's methods before calling __builtin__.dict
, which is precisely what we want.
这意味着,当OrderedDefaultDict语句的实例初始化时,它转向OrderedDict的init,但是这个实例反过来将在调用__builtin__之前调用defaultdict的方法。这正是我们想要的。
#3
15
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.
这是另一个解决方案,如果您的用例很简单,就像我的一样,并且您并不一定要在代码中添加DefaultOrderedDict类实现的复杂性。
from collections import OrderedDict
keys = ['a', 'b', 'c']
items = [(key, None) for key in keys]
od = OrderedDict(items)
(None
is my desired default value.)
(None是我想要的默认值。)
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:
更新3/13/17 -我了解了这个用例的便利功能。和上面一样,但是您可以省略行项=…就:
od = OrderedDict.fromkeys(keys)
Output:
输出:
OrderedDict([('a', None), ('b', None), ('c', None)])
And if your keys are single characters, you can just pass one string:
如果你的键是单个字符,你可以只传递一个字符串:
OrderedDict.fromkeys('abc')
This has the same output as the two examples above.
它的输出与上面两个示例相同。
You can also pass a default value as the second arg to OrderedDict.fromkeys(...)
.
您还可以将一个默认值作为第二个arg传递给OrderedDict.fromkeys(…)。
#4
12
If you want a simple solution that doesn't require a class, you can just use OrderedDict.setdefault(key, default=None)
or OrderedDict.get(key, default=None)
. If you only get / set from a few places, say in a loop, you can easily just setdefault.
如果您想要一个不需要类的简单解决方案,您可以使用OrderedDict。setdefault(键,默认= None)或OrderedDict。得到(键,默认= None)。如果您只从几个地方(比如在循环中)获取/设置,您可以轻松地设置为setdefault。
totals = collections.OrderedDict()
for i, x in some_generator():
totals[i] = totals.get(i, 0) + x
It is even easier for lists with setdefault
:
setdefault列表更容易:
agglomerate = collections.OrderedDict()
for i, x in some_generator():
agglomerate.setdefault(i, []).append(x)
But if you use it more than a few times, it is probably better to set up a class, like in the other answers.
但是,如果您多次使用它,那么最好像其他答案一样建立一个类。
#5
5
A simpler version of @zeekay 's answer is:
@zeekay的回答更简单:
from collections import OrderedDict
class OrderedDefaultListDict(OrderedDict): #name according to default
def __missing__(self, key):
self[key] = value = [] #change to whatever default you want
return value
#6
0
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:
我测试了默认的命令,发现它也是有序的!也许这只是一个巧合,但无论如何你可以使用排序函数:
sorted(s.items())
i think it's simpler
我认为这是更简单
#7
0
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.
基于@NickBread的简单而优雅的解决方案。有一个稍微不同的API来设置工厂,但是好的默认值总是很好。
class OrderedDefaultDict(OrderedDict):
factory = list
def __missing__(self, key):
self[key] = value = self.factory()
return value
#1
71
The following (using a modified version of this recipe) works for me:
下面(使用这个食谱的修改版本)为我工作:
from collections import OrderedDict, Callable
class DefaultOrderedDict(OrderedDict):
# Source: http://*.com/a/6190500/562769
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not isinstance(default_factory, Callable)):
raise TypeError('first argument must be callable')
OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
OrderedDict.__repr__(self))
#2
33
Here is another possibility, inspired by Raymond Hettinger's super() Considered Super, tested on Python 2.7.X and 3.4.X:
这是另一种可能,灵感来自Raymond Hettinger的super(),被认为是super,在Python 2.7上测试过。X和3.4.X:
from collections import OrderedDict, defaultdict
class OrderedDefaultDict(OrderedDict, defaultdict):
def __init__(self, default_factory=None, *args, **kwargs):
#in python3 you can omit the args to super
super(OrderedDefaultDict, self).__init__(*args, **kwargs)
self.default_factory = default_factory
If you check out the class's MRO (aka, help(OrderedDefaultDict)
), you'll see this:
如果您查看类的MRO (aka, help(OrderedDefaultDict de)),您将看到以下内容:
class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict)
| Method resolution order:
| OrderedDefaultDict
| collections.OrderedDict
| collections.defaultdict
| __builtin__.dict
| __builtin__.object
meaning that when an instance of OrderedDefaultDict
is initialized, it defers to the OrderedDict
's init, but this one in turn will call the defaultdict
's methods before calling __builtin__.dict
, which is precisely what we want.
这意味着,当OrderedDefaultDict语句的实例初始化时,它转向OrderedDict的init,但是这个实例反过来将在调用__builtin__之前调用defaultdict的方法。这正是我们想要的。
#3
15
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.
这是另一个解决方案,如果您的用例很简单,就像我的一样,并且您并不一定要在代码中添加DefaultOrderedDict类实现的复杂性。
from collections import OrderedDict
keys = ['a', 'b', 'c']
items = [(key, None) for key in keys]
od = OrderedDict(items)
(None
is my desired default value.)
(None是我想要的默认值。)
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:
更新3/13/17 -我了解了这个用例的便利功能。和上面一样,但是您可以省略行项=…就:
od = OrderedDict.fromkeys(keys)
Output:
输出:
OrderedDict([('a', None), ('b', None), ('c', None)])
And if your keys are single characters, you can just pass one string:
如果你的键是单个字符,你可以只传递一个字符串:
OrderedDict.fromkeys('abc')
This has the same output as the two examples above.
它的输出与上面两个示例相同。
You can also pass a default value as the second arg to OrderedDict.fromkeys(...)
.
您还可以将一个默认值作为第二个arg传递给OrderedDict.fromkeys(…)。
#4
12
If you want a simple solution that doesn't require a class, you can just use OrderedDict.setdefault(key, default=None)
or OrderedDict.get(key, default=None)
. If you only get / set from a few places, say in a loop, you can easily just setdefault.
如果您想要一个不需要类的简单解决方案,您可以使用OrderedDict。setdefault(键,默认= None)或OrderedDict。得到(键,默认= None)。如果您只从几个地方(比如在循环中)获取/设置,您可以轻松地设置为setdefault。
totals = collections.OrderedDict()
for i, x in some_generator():
totals[i] = totals.get(i, 0) + x
It is even easier for lists with setdefault
:
setdefault列表更容易:
agglomerate = collections.OrderedDict()
for i, x in some_generator():
agglomerate.setdefault(i, []).append(x)
But if you use it more than a few times, it is probably better to set up a class, like in the other answers.
但是,如果您多次使用它,那么最好像其他答案一样建立一个类。
#5
5
A simpler version of @zeekay 's answer is:
@zeekay的回答更简单:
from collections import OrderedDict
class OrderedDefaultListDict(OrderedDict): #name according to default
def __missing__(self, key):
self[key] = value = [] #change to whatever default you want
return value
#6
0
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:
我测试了默认的命令,发现它也是有序的!也许这只是一个巧合,但无论如何你可以使用排序函数:
sorted(s.items())
i think it's simpler
我认为这是更简单
#7
0
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.
基于@NickBread的简单而优雅的解决方案。有一个稍微不同的API来设置工厂,但是好的默认值总是很好。
class OrderedDefaultDict(OrderedDict):
factory = list
def __missing__(self, key):
self[key] = value = self.factory()
return value