Home >Backend Development >Python Tutorial >Does python dictionary support bidirectional indexing?
The dictionary in Python is another mutable container model and can store any type of object. Each key-value (key=>value) pair in the dictionary is separated by a colon (:), and each pair is separated by a comma (,). The entire dictionary is included in curly braces ({}), and the dictionary is unordered. , press the key to get the value.
The dictionary module provides three classes to handle some operations of one-to-one mapping types
'bidict', 'inverted', 'namedbidict'
>>> import bidict >>> dir(bidict) ['MutableMapping', '_LEGALNAMEPAT', '_LEGALNAMERE', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bidict', 'inverted', 'namedbidict', 're', 'wraps']
1.bidict class:
>>> 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 class, invert the key value of the dictionary
>>> 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'})
The above is the detailed content of Does python dictionary support bidirectional indexing?. For more information, please follow other related articles on the PHP Chinese website!