Python中使用bidict模塊雙向字典結(jié)構(gòu)的奇技淫巧
快速入門
模塊提供三個(gè)類來(lái)處理一對(duì)一映射類型的一些操作
'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 #反轉(zhuǎn)字典
bidict({'b': 'a'})
>>> dict(D) #轉(zhuǎn)為普通字典
{'a': 'b'}
>>> D['c']='c' #添加元素,普通字典的方法都可以用
>>> D
bidict({'a': 'b', 'c': 'c'})
2.inverted類,反轉(zhuǎn)字典的鍵值
>>> 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'})
更多內(nèi)容
如果你不喜歡冒號(hào)的方式,可以使用namedbidict類給雙向字典起2個(gè)別名。這樣對(duì)外會(huì)提供正向和逆向的2個(gè)子字典。實(shí)際上還是以一個(gè)雙向 字典的形式存在:
>>> HTMLEntities = namedbidict('HTMLEntities', 'names', 'codepoints')
>>> entities = HTMLEntities({'lt': 60, 'gt': 62, 'amp': 38}) # etc
>>> entities.names['lt']
60
>>> entities.codepoints[38]
'amp'
還可以使用一元的逆運(yùn)算符"~"獲取bidict逆映射字典。
>>> import bidict
>>> from bidict import bidict
>>> husbands2wives = bidict({'john': 'jackie'})
>>> ~husbands2wives
bidict({'jackie': 'john'})
以下情況注意添加括號(hào),因?yàn)?span style="color: #ff0000">~的優(yōu)先級(jí)低于中括號(hào):
>>> import bidict
>>> from bidict import bidict
>>> husbands2wives = bidict({'john': 'jackie'})
>>> ~husbands2wives
bidict({'jackie': 'john'})
以下情況注意添加括號(hào),因?yàn)閪的優(yōu)先級(jí)低于中括號(hào):
>>> (~bi)['one'] 1
bidict不是dict的子類,但它的API的是dict的超集(但沒(méi)有fromkeys方法,改用了MutableMapping接 口)。
迭代器類inverted會(huì)翻轉(zhuǎn)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可以和字典進(jìn)行比較
>>> 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)]
相關(guān)文章
關(guān)于numpy.where()函數(shù) 返回值的解釋
今天小編就為大家分享一篇關(guān)于numpy.where()函數(shù) 返回值的解釋,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
python?pygame英雄循環(huán)飛行及作業(yè)示例
這篇文章主要為大家介紹了python?pygame英雄循環(huán)飛行及作業(yè)實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
在linux系統(tǒng)下安裝python librtmp包的實(shí)現(xiàn)方法
今天小編就為大家分享一篇在linux系統(tǒng)下安裝python librtmp包的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python解決asyncio文件描述符最大數(shù)量限制的問(wèn)題
這篇文章主要介紹了Python解決asyncio文件描述符最大數(shù)量限制的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
python如何用pymodbus庫(kù)進(jìn)行modbus tcp通信
這篇文章主要介紹了python如何用pymodbus庫(kù)進(jìn)行modbus tcp通信問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
從Pytorch模型pth文件中讀取參數(shù)成numpy矩陣的操作
這篇文章主要介紹了從Pytorch模型pth文件中讀取參數(shù)成numpy矩陣的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
Python設(shè)計(jì)模式之中介模式簡(jiǎn)單示例
這篇文章主要介紹了Python設(shè)計(jì)模式之中介模式,簡(jiǎn)單介紹了中介模式的概念、功能,并結(jié)合實(shí)例形式給出了Python定義與使用中介模式的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01

