大家讲道理2017-04-18 10:09:26
You can implement this structure yourself.
In the example below, AutoVivification inherits from dict
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
We can use AutoVivification like this:
item = AutoVivification()
item['20161101']["age"] = 20
item['20161102']['num'] = 30
print item
Output:
{'20161101': {'age': 20}, '20161102': {'num': 30}}
In addition, there is another implementation method of AutoVivification, which is to directly overload dict's __missing__
magic method. Think of it as an extension.
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __missing__(self, key):
value = self[key] = type(self)()
return value
One more thing, Python 2.5 and later versions added the collections.defaultdict
type, which can customize a more scalable dict type. collections.defaultdict
类型,该类型可以自定义扩展性更强大的dict类型。
文档中指出,其实现原理就是重载了 __missing__
The documentation points out that the implementation principle is to overload the
item = defaultdict(dict) # 其实现与AutoVivification的实现完全一样
item['20161101']["age"] = 20
item['20161102']['num'] = 30
print item
__missing__
defaultdict constructs a dict type whose first parameter is its default_factory. When PHP中文网2017-04-18 10:09:26
I will attach the usage of defaultdict package:
from collections import defaultdict
item = defaultdict(dict)
item['20161101']['age'] = 20
print item
Output:
defaultdict(<type 'dict'>, {'20161101': {'age': 20}})
This way you can achieve the desired effect,
Added:
defaultdict() receives a default parameter, which can be a type name or any callable function without parameters
This is very easy to use
item = defaultdict(lambda:0)
print item['num']
Output:
0