python 多层级自动赋值字典

python 多层级自动赋值字典

  • dict 只能单层级赋值

item['20161101'] = 2

  • defaultdict 只能双层级赋值

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

  • 实现多层级自动赋值 除了可以重载__getitem__魔术方法,也可以实现__missing__魔术方法
  1. 重载__getitem__魔术方法:
def __getitem__(self, item):
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()
        return value
  1. 实现__missing__魔术方法:
def __missing__(self, key):
	value = self[key] = type(self)()
	return value
  1. 使用方法:
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)

你可能感兴趣的:(python)