python的工具库谁写_python工具库库介绍-bidict: 双向字典

快速入门

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

>>> husbands2wives['john'] # the forward mapping is just like with dict

'jackie'

>>> husbands2wives[:'jackie'] # use slice for the inverse mapping

'john'

" 在切片的前面加上冒号表示逆映射。跟数据的切片类似,husbands2wives["john"]和 husbands2wives["john":]的效果一样。

更多内容

如果你不喜欢冒号的方式,可以使用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)]

技术支持qq群: 144081101 591302926 567351477 钉钉免费群:21745728

类型:翻译加整理

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值