2012-06-28 33 views
0

这可能是一个愚蠢的问题,但由于某种原因,目前解决方案逃脱了我。词典或地图与字符串或整数作为在Python中的关键?

我希望快速有效地访问列表格式的数据。因此,例如一个问题列表:

q = {} 
q[1] = "my first string" 
q[2] = "my second string" 
q[3] = "my third string" 

我可以很容易地找到问题2的字符串是通过做q [2]。但我也想通过索引Q随字符串检索问题编号:

q["my second string"] -> gives 2 as answer 

我想这样做没有遍历键(击败字典的目的),并希望避免定义第二使用字符串作为密钥的字典可避免浪费的内存。这可能吗?

最终原因是我想访问说q [2]或q [“我的第二个字符串”]并获取与问题2相关的数据,无论是使用数字还是字符串作为关键字数据。这是可能的,而不必迭代所有的密钥,同时避免数据重复?

+0

你不能这样做...... –

+0

dicts arn't双向,所以你要么需要第二个字典或迭代。没有其他办法。 – mata

+0

可能重复的[有效的双向哈希表在Python?](http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python) – ecatmur

回答

1

您可以使用OrderedDict,但对于其中一个方向,它不会像普通字典查找那样高效。

from collections import OrderedDict 
q = OrderedDict() 
q["my first string"] = 1 
q["my second string"] = 2 
q["my third string"] = 3 
# Now you have normal key lookups on your string as a normal dict, and to get the order 
q.values()[1] # To get the second value out 
# To get the key, value pair of the second entry 
q.items()[1] 
# Would return `('my second string', 2)` 
2

有有和strint混合物作为键

>>> q = {} 
>>> q[1] = "my first string" 
>>> q[2] = "my second string" 
>>> q[3] = "my third string" 
>>> q.update({v:k for k,v in q.items()}) 
>>> q["my second string"] 
2 
+0

python是真棒..! :) – Lipis

+0

我想避免字典中的数据重复。 – doorfly

+0

@doorfly,没有数据重复,只是引用是重复的 –

0
class MyDict(dict): 
    def __init__(self, **kwargs): 
     super(MyDict, self).__init__(**kwargs) 
     for k, v in kwargs.iteritems(): 
      self[v] = k 
    def __setitem__(self, key, val): 
     super(MyDict, self).__setitem__(key, val) 
     super(MyDict, self).__setitem__(val, key) 

d = MyDict(a=1, b=2) 
print d[1] # "a" 
print d[2] # "b" 
d['c'] = 3 
print d[3] # "c" 
相关问题