Python中使用bidict模块双向字典结构的奇技淫巧

yipeiwu_com6年前Python基础

快速入门

模块提供三个类来处理一对一映射类型的一些操作
'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)]

相关文章

python 统计文件中的字符串数目示例

题目: 一个txt文件中已知数据格式为: C4D C4D/maya C4D C4D/su C4D/max/AE 统计每个字段出现的次数,比如C4D、maya 先读取文件,将文件中的数据抽...

Python3中详解fabfile的编写

fab命令好似结合我们编写的fabfile.py(其它文件名必须添加-f filename应用)来搭配使用的,部分命令行参数可以通过相应的方法来替代,使之更加灵活,例如"-H 192.1...

Python实现迭代时使用索引的方法示例

本文实例讲述了Python实现迭代时使用索引的方法。分享给大家供大家参考,具体如下: 索引迭代 Python中,迭代永远是取出元素本身,而非元素的索引。 对于有序集合,元素确实是有索引的...

Python如何实现MySQL实例初始化详解

前言 相信每位程序员对mysql应该都不陌生,MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。我们在日常开发中少不了要接触mys...

python getopt模块使用实例解析

这篇文章主要介绍了python getopt模块使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 官方介绍地址: ...