基于字典内部键的嵌套defaultdict

时间:2016-06-15 14:54:55

标签: python dictionary nested defaultdict

我试图根据键值在defaultdict中创建一个defaultdict。我的想法在这里可能完全错误,但这里是基本默认用户的代码;

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

    }
}

但是如果我想像这样添加一个密钥作为defaultdict呢?

[MulticastAttributeUsage(PersistMetaData = true)]
public class TlvContractAttribute : TypeLevelAspect
{
    public override void CompileTimeInitialize(Type target, AspectInfo aspectInfo)
    {
        Dictionary<int, PropertyInfo> indexes = new Dictionary<int, PropertyInfo>();

        foreach (PropertyInfo propertyInfo in target.GetProperties())
        {
            TlvMemberAttribute memberAttr =
                propertyInfo.GetCustomAttributes()
                    .Where(x => x is TlvMemberAttribute)
                    .Cast<TlvMemberAttribute>()
                    .SingleOrDefault();

            if (memberAttr == null)
            {
                Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR001",
                    "Property {0} should be marked by TlvMemberAttribute.", propertyInfo);

                continue;
            }

            if (indexes.ContainsKey(memberAttr.Index))
            {
                Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR002",
                    "Property {0} marked by TlvMemberAttribute uses Index {1}, which is already used by property {2}.",
                    propertyInfo, memberAttr.Index, indexes[memberAttr.Index]);

                continue;
            }

            indexes[memberAttr.Index] = propertyInfo;
        }
    }
}

在上面我怎么能做出关键2&#39;一个默认的?这甚至可能还是我以错误的方式解决问题?

1 个答案:

答案 0 :(得分:0)

你绝对可以拥有一个“递归”的默认词:

>>> 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>, {})}})}})

但是,在不同级别更换密钥的名称可能需要一些特殊的外壳,这会使代码更麻烦......