简体   繁体   English

基于字典中的键的嵌套defaultdict

[英]nested defaultdict based on a key inside dictionary

I'm trying to create a defaultdict within a defaultdict based on a key value. 我正在尝试基于键值在defaultdict中创建defaultdict。 My thinking may be completely wrong here, but here's the code for a basic defaultdict; 我的想法可能在这里是完全错误的,但这是基本defaultdict的代码;

def record():
    return {
        'count': 0,
        'key1': Counter(),      
    }

1_record = defaultdict(record)

But what if I want to add a key as a defaultdict like this; 但是,如果我想像这样添加一个键作为defaultdict怎么办?

def record():
    return {
        'count': 0,
        'key1': Counter(),
        'key2': {
            'count': 0,
            'nested_key1': Counter()

    }
}

In the above how could I make 'key2' a defaultdict? 在上面我怎样才能使'key2'为defaultdict? Is this even possible or am I approaching the problem the wrong way? 这甚至可能还是我以错误的方式解决问题?

You definitely can have a "recursive" defaultdict: 您绝对可以有一个“递归”默认值:

>>> from collections import defaultdict
>>> def record():
...   return {
...     'key': defaultdict(record)
...   }
... 
>>> d = defaultdict(record)
>>> 
>>> d['foo']
{'key': defaultdict(<function record at 0x10b396f50>, {})}
>>> d['foo']['key']['bar']
{'key': defaultdict(<function record at 0x10b396f50>, {})}
>>> d
defaultdict(<function record at 0x10b396f50>, {'foo': {'key': defaultdict(<function record at 0x10b396f50>, {'bar': {'key': defaultdict(<function record at 0x10b396f50>, {})}})}})

However, swapping out the names of the keys at different levels would probably require some special-casing and would make the code a bit more messy... 但是,换出不同级别的键名称可能需要一些特殊的框,这会使代码更加混乱……

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM