首頁  >  文章  >  後端開發  >  Python中使用bidict模組雙向字典結構的奇技淫巧

Python中使用bidict模組雙向字典結構的奇技淫巧

WBOY
WBOY原創
2016-08-04 08:55:422312瀏覽

快速入門

模組提供三個類別來處理一對一映射類型的一些操作
'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'})

更多內容

如果你不喜歡冒號的方式,可以使用namedbidict類別給雙向字典取2個別名。這樣對外會提供正向和逆向的2個子字典。實際上還是以一個雙向 字典的形式存在:

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

也可以使用一元的逆運算子"~"來取得bidict逆映射字典。

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

以下情況注意添加括號,因為~的優先順序低於中括號

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

以下情況注意添加括號,因為~的優先順序低於中括號:

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

bidict不是dict的子類,但它的API的是dict的超集(但沒有fromkeys方法,改用了MutableMapping 口)。

迭代器類別inverted會翻轉key和value,如:

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

bidict的invert()方法和inverted類似。依賴模組:collections中的MutableMapping,functools中的wraps,re。

bidict可以和字典進行比較

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

其他字典通用的方法,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)]

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn