时间:2021-07-01 10:21:17 帮助过:606人阅读
字典模块提供三个类来处理一对一映射类型的一些操作
'bidict', 'inverted', 'namedbidict'
>>> import bidict >>> dir(bidict) ['MutableMapping', '_LEGALNAMEPAT', '_LEGALNAMERE', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bidict', 'inverted', 'namedbidict', 're', 'wraps']
1.bidict类:
>>> from bidict import bidict >>> D=bidict({'a':'b'}) >>> D['a'] 'b' >>> D[:'b'] 'a' >>> ~D #反转字典 bidict({'b': 'a'}) >>> dict(D) #转为普通字典 {'a': 'b'} >>> D['c']='c' #添加元素,普通字典的方法都可以用 >>> D bidict({'a': 'b', 'c': 'c'})
2.inverted类,反转字典的键值
>>> seq = [(1, 'one'), (2, 'two'), (3, 'three')] >>> list(inverted(seq)) [('one', 1), ('two', 2), ('three', 3)]
3.namedbidict(mapname, fwdname, invname):
>>> CoupleMap = namedbidict('CoupleMap', 'husbands', 'wives') >>> famous = CoupleMap({'bill': 'hillary'}) >>> famous.husbands['bill'] 'hillary' >>> famous.wives['hillary'] 'bill' >>> famous.husbands['barack'] = 'michelle' >>> del famous.wives['hillary'] >>> famous CoupleMap({'barack': 'michelle'})
以上就是python字典支持双向索引吗的详细内容,更多请关注Gxl网其它相关文章!