Home  >  Article  >  Backend Development  >  The trick of using bidict module bidirectional dictionary structure in Python

The trick of using bidict module bidirectional dictionary structure in Python

WBOY
WBOYOriginal
2016-08-04 08:55:422310browse

Quick Start

The 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 values ​​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'})

More content

If you don’t like the colon method, you can use the namedbidict class to give the bidirectional dictionary 2 aliases. In this way, two sub-dictionaries, forward and reverse, will be provided to the outside world. In fact, it still exists in the form of a two-way dictionary:

>>> HTMLEntities = namedbidict('HTMLEntities', 'names', 'codepoints')
>>> entities = HTMLEntities({'lt': 60, 'gt': 62, 'amp': 38}) # etc
>>> entities.names['lt']
60
>>> entities.codepoints[38]
'amp'

You can also use the unary inverse operator "~" to obtain the bidict inverse mapping dictionary.

>>> import bidict
>>> from bidict import bidict
>>> husbands2wives = bidict({'john': 'jackie'})
>>> ~husbands2wives
bidict({'jackie': 'john'})

Be careful to add parentheses in the following situations, because the priority of ~ is lower than that of square brackets:

>>> import bidict
>>> from bidict import bidict
>>> husbands2wives = bidict({'john': 'jackie'})
>>> ~husbands2wives
bidict({'jackie': 'john'})

Be careful to add parentheses in the following situations, because ~ has a lower priority than square brackets:

>>> (~bi)['one']
1

bidict is not a subclass of dict, but its API is a superset of dict (but there is no fromkeys method, and the MutableMapping interface is used instead).

The iterator class inverted will flip the key and value, such as:

>>> seq = [(1, 'one'), (2, 'two'), (3, 'three')]
>>> list(inverted(seq))
[('one', 1), ('two', 2), ('three', 3)]

bidict’s invert() method is similar to inverted. Dependent modules: MutableMapping in collections, wraps in functools, re.

bidict can be compared with dictionaries

>>> bi == bidict({1:'one'})
>>> bi == dict([(1, 'one')])
True

Methods common to other dictionaries are also supported by bidict:

>>> bi.get('one')
1
>>> bi.setdefault('one', 2)
1
>>> bi.setdefault('two', 2)
2
>>> len(bi) # calls __len__
2
>>> bi.pop('one')
1
>>> bi.popitem()
('two', 2)
>>> bi.inv.setdefault(3, 'three')
'three'
>>> bi
bidict({'three': 3})
>>> [key for key in bi] # calls __iter__, returns keys like dict
['three']
>>> 'three' in bi # calls __contains__
True
>>> list(bi.keys())
['three']
>>> list(bi.values())
[3]
>>> bi.update([('four', 4)])
>>> bi.update({'five': 5}, six=6, seven=7)
>>> sorted(bi.items(), key=lambda x: x[1])
[('three', 3), ('four', 4), ('five', 5), ('six', 6), ('seven', 7)]

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn