# 1.UserDict
dict的派生类,可用来实现自定义属性的dict
,如以下,定义禁止删除dict
中的元素
Creating a Dictionary where
deletion is not allowed
from collections import UserDict, namedtuple, Counter, ChainMap
class MyDict(UserDict):
# Function to stop pop from
# dictionary
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop popitem
# from Dictionary
def popitem(self, s = None):
raise RuntimeError("Deletion not allowed")
md = MyDict()
md["name"] = "Tom"
print(md)
# md.pop("name") # RuntimeError
# 2.namedtuple
带命名字段的tuple
工厂函数,返回一个类型为typename
的tuple
派生类,新返回的tuple
子类可用于创建类tuple
对象,
不过其带有字段属性,可通过字段属性访问,也可通过下标访问。
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Point = namedtuple("Point", ['x', 'y'])
p = Point(x=11, y=22)
x, y = p
print(x, y)
print(p[0], p.x)
# 11 22
# 11 11
# 3.Counter
Counter设计用来快速实现元素统计计数的,是dict
的子类,用以给可哈希对象计数。可用来返回n最常见元素等。
两两之间还能实现+,-,&,|
等运算
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
print(cnt)
print(cnt.most_common(2))
print(cnt+cnt)
# Counter({'blue': 3, 'red': 2, 'green': 1})
# [('blue', 3), ('red', 2)]
# Counter({'blue': 6, 'red': 4, 'green': 2})
# 4.ChainMap
ChainMap
用于将多个dict
或其他mapping
类型的对象组合起来生成可更新的视图,常用的属性有maps
返回
所有的输入map
对象,parents
返回另一个ChainMap
对象,不包含第一个map
,new_child
返回一个带新元素的
ChainMap
,主要用于管理多个上下文,实际上ChainMap查询的字典实际上还是原来的字典的引用。
baseline = {'music': 'bach', 'art': 'rembrandt'}
adjustments = {'art': 'van gogh', 'opera': 'carmen'}
c = ChainMap(adjustments, baseline)
print(c.maps)
# [{'art': 'van gogh', 'opera': 'carmen'}, {'music': 'bach', 'art': 'rembrandt'}]
print(c.parents)
# ChainMap({'music': 'bach', 'art': 'rembrandt'})
nd = {"a":"b"}
nc = c.new_child(nd)
print(nc)
# ChainMap({'a': 'b'}, {'art': 'van gogh', 'opera': 'carmen'}, {'music': 'bach', 'art': 'rembrandt'})
nc['a'] = "bb"
print(nd)
# {'a': 'bb'}