python的可逆字典 [英] Reversible dictionary for python
问题描述
我想以类似于字典的形式在Python中存储一些数据: {1:'a',2:'b'}
。每个值都将是独一无二的,而不仅仅是其他的值,而且在键之间。
I'd like to store some data in Python in a similar form to a dictionary: {1:'a', 2:'b'}
. Every value will be unique, not just among other values, but among keys too.
有没有一个简单的数据结构可以用来获取相应的对象,无论是否请问使用键或值?例如:
Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:
>>> a = {1:'a', 2:'b'}
>>> a[1]
'a'
>>> a['b']
2
>>> a[3]
KeyError
'keys'是标准的python int,值是短(<256char)的字符串。
The 'keys' are standard python ints, an the values are short (<256char) strings.
我目前的解决方案是创建一个反转的字典,并在原始字典中找不到结果进行搜索: p>
My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:
pointsreversed = dict((v, k) for k, v in points.iteritems())
def lookup(key):
return points.get(key) or pointsreversed.key()
两倍的空间,这不是很大(我的字典可以达到几百百万),平均慢50%。
This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.
编辑:如几个答案,两个dache不会增加内存使用量,因为它只是字典,而不是内容中的重复。
as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.
有没有解决方案可以改进这个?
Is there a solution that improves on this?
推荐答案
相关文章:
Python 1:1 mappings
当然,如果所有值和键都是唯一的,你不能只使用一个字典,并且最初插入key:value和value:key?
Of course, if all values and keys are unique, couldn't you just use a single dictionary, and insert both key:value and value:key initially?
这篇关于python的可逆字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!