item['20161101'] = 2
item['20161101']["age"] = 2
使用方法:
import collections
bag = ['apple', 'orange', 'cherry', 'apple','apple', 'cherry', 'blueberry']
count = collections.defaultdict(int)
for fruit in bag:
count[fruit] += 1
输出:
defaultdict(<class 'int'>, {'apple': 3, 'orange': 1, 'cherry': 2, 'blueberry': 1})
item['20161101']["age"]["444"] = 2
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def __missing__(self, key):
value = self[key] = type(self)()
return value
class multidict(dict):
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
item = multidict()
item['20161101']["age"] = 20
item['20161102']['num'] = 30
print(item)