这可能是一个愚蠢的问题,但由于某种原因,解决方案暂时逃脱了我。
我希望能够快速有效地访问列表格式的数据。例如,问题列表:
q = {}
q[1] = "my first string"
q[2] = "my second string"
q[3] = "my third string"
我可以通过q [2]轻松找到问题2的字符串。但我还想通过用字符串索引q来检索问题编号:
q["my second string"] -> gives 2 as answer
我想这样做而不迭代键(违背字典的目的)并且喜欢避免使用字符串作为键来定义第二个字典以避免浪费内存。这可能吗?
最终的原因是我想访问说q [2]或q [“我的第二个字符串”]并获取与问题2相关的数据,无论是使用数字还是字符串作为该数据的关键字。这是否可以在不必迭代所有键的同时避免数据重复?
答案 0 :(得分:2)
将int
和str
混合为
>>> 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
答案 1 :(得分: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 :(得分:0)
有人问Efficient bidirectional hash table in Python?
答案保持不变 - 使用http://pypi.python.org/pypi/bidict
中的bidict
答案 3 :(得分: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"