• 问题描述
• 解决方案
• 自动逐层创建字典
• 实例创建及类型转换
• 潜在问题

## 问题描述

``````a = {'a': 'a'}
a['b']['c'] = 1  # 这里会报错，dict不会自动创建多层结构``````

## 解决方案

``````class compositedict(dict):
def __init__(self, seq=None, **kwargs):
super(compositedict, self).__init__()
if seq is None:
pass
elif isinstance(seq, dict):
for k, v in seq.items():
self[k] = compositedict(v) if isinstance(v, dict) else v
else:
for k, v in seq:
self[k] = compositedict(v) if isinstance(v, dict) else v
for k, v in kwargs.items():
self[k] = compositedict(v) if isinstance(v, dict) else v

def __getitem__(self, item):
if not self.__contains__(item):
self[item] = compositedict()
return super(compositedict, self).__getitem__(item)``````

### 自动逐层创建字典

`[]`获取键值的时候判断是否存在，不存在则创建新`compositedict`，保证能递归到更深层

``````class compositedict(dict):
def __getitem__(self, item):
if not self.__contains__(item):
self[item] = compositedict()
return super(compositedict, self).__getitem__(item)``````

``````a = compositedict()
a['a']['b']['c'] = 'd'
print(a)
print(type(a['b']))``````

### 实例创建及类型转换

``````a = {'xxx': {'yyy': {'zzz': 'a'}}}
b = compositedict(a)
b['xxx']['vvv']['www'] = 'b'``````

``````def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list.  For example:  dict(one=1, two=2)
# (copied from class doc)
"""
pass``````

• `dict({'a': {'b': 'c'}})`
• `dict([('a', {'b': 'b'}), ('c', 'd')])`
• `dict(a={'b': 'b'})`

``````class compositedict(dict):
def __init__(self, seq=None, **kwargs):
super(compositedict, self).__init__()
if seq is None:  # 需要特殊处理None情况
pass
elif isinstance(seq, dict):  # 处理seq为dict的情况
for k, v in seq.items():
self[k] = compositedict(v) if isinstance(v, dict) else v
else:
for k, v in seq:  # 处理seq为列表结构的情况
self[k] = compositedict(v) if isinstance(v, dict) else v
for k, v in kwargs.items():  # 对kwargs中的键值对同样递归处理
self[k] = compositedict(v) if isinstance(v, dict) else v

def __getitem__(self, item):
if not self.__contains__(item):
self[item] = compositedict()
return super(compositedict, self).__getitem__(item)``````

``````a = compositedict({'a': {'b': {'c': 'c'}}})
print(type(a['a']))
print(type(a['a']['b']))
print(type(a['a']['d']))
print(a)
b = compositedict([('a', {'b': 'b'})])
print(type(b['a']))
c = compositedict(a={'a': 'b'})
print(type(c['a']))``````

## 潜在问题

``````a = compositedict()
b = 0 if a['a'].get('b') else 1
print(a)``````