Immutable Set
setは可変(Mutable)なので辞書のキーにできない。辞書のキーにするには不変(Immutable)なsetを使用すれば良い。ビルトインfrozensetは『Python Phrasebook』のなか見!検索で見ていて今日初めて知った。
>>> mt_s = set([1,2,9]) >>> im_s = frozenset([1,2,9]) >>> d = {} >>> d[mt_s] = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: set objects are unhashable >>> d[im_s] = 1 >>> d[im_s] 1 >>> mt_s.add(3) >>> im_s.add(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add'
>>> from pprint import pprint >>> pprint( ... sorted(set(dir(mt_s)) - set(dir(im_s))) ... ) ) ['__iand__', '__ior__', '__isub__', '__ixor__', 'add', 'clear', 'difference_update', 'discard', 'intersection_update', 'pop', 'remove', 'symmetric_difference_update', 'update'] >>> >>> pprint( ... sorted(set(dir(im_s)) - set(dir(mt_s))) ... ) []