本文摘自php中文网,作者anonymity,侵删。
Python中的字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,字典是无序的,按键取值。
字典模块提供三个类来处理一对一映射类型的一些操作
'bidict', 'inverted', 'namedbidict'
1 2 3 4 | >>> import bidict
>>> dir(bidict)
[ 'MutableMapping' , '_LEGALNAMEPAT' , '_LEGALNAMERE' , '__builtins__' , '__doc__' ,
'__file__' , '__name__' , '__package__' , 'bidict' , 'inverted' , 'namedbidict' , 're' , 'wraps' ]
|
1.bidict类:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> 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类,反转字典的键值
1 2 3 | >>> seq = [(1, 'one' ), (2, 'two' ), (3, 'three' )]
>>> list(inverted(seq))
[( 'one' , 1), ( 'two' , 2), ( 'three' , 3)]
|
3.namedbidict(mapname, fwdname, invname):
1 2 3 4 5 6 7 8 9 10 | >>> 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' })
|
以上就是python字典支持双向索引吗的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python如何实现zabbix-api监控(附代码)
Python使用openpyxl库修改excel表格数据方法
怎么用Python
Python的注释有哪些
Python装饰器原理与用法分析
Python基础学习之列表的介绍
Python中eval是什么意思?
Python中的元类(metaclass)是什么
Python中paramiko模块实现远程控制以及传输的示例
Python线程下事件用法的简单介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python字典支持双向索引吗