Introduction to python tool library bidict: Bidirectional Dictionary

Posted by Vbabiy on Tue, 24 Dec 2019 16:33:55 +0100

quick get start

>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'

"Prefix the slice with a colon to indicate an inverse mapping. Similar to data slicing, husbands2wives["john"] has the same effect as husbands2wives["john":].

More content

If you don't like colons, you can use the namedbidict class to give the two-way dictionary two aliases. In this way, two sub dictionaries, forward and reverse, will be provided externally. 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 get the dictionary of inverse mapping of bidict.

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

Pay attention to adding brackets in the following cases, because the priority of ~ is lower than that of brackets:

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

Pay attention to adding brackets in the following cases, because the priority of ~ is lower than that of brackets:

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

bidict is not a subclass of dict, but its API is a superset of dict (without the fromkeys method, 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. Dependency module: MutableMapping in collections, wraps and re in functools.

bidict can be compared with dictionaries

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

Other common methods of dictionaries, bidict also supports:

>>> 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)]
  • Technical support qq group: 144081101 591302926 567351477 nail free group: 21745728
  • Type: translation and arrangement

Reference material

Topics: github Lambda Python