python - 如何为一个dict字典进行多层级赋值?
ringa_lee
ringa_lee 2017-04-18 10:07:26
0
2
1425
ringa_lee
ringa_lee

ringa_lee

reply all (2)
大家讲道理

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 thecollections.defaultdicttype, which can customize a more scalable dict type.collections.defaultdict类型,该类型可以自定义扩展性更强大的dict类型。
文档中指出,其实现原理就是重载了__missing__The documentation points out that the implementation principle is to overload the

method. AutoVivification can also be expressed like this:

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
is called, the return value is constructed using default_factory. More examples of defaultdict
    洪涛

    I will attach the usage of defaultdict package:

    from collections import defaultdict item = defaultdict(dict) item['20161101']['age'] = 20 print item

    Output:

    defaultdict(, {'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
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!