python中以字符串或整数作为键的字典或映射?

python中以字符串或整数作为键的字典或映射?,python,data-structures,Python,Data Structures,这可能是一个愚蠢的问题,但出于某种原因,我目前无法找到解决办法 我希望能够快速高效地访问列表格式的数据。例如,一系列问题: 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 = {}
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相关的数据,无论是使用数字还是字符串作为该数据的键。在避免数据重复的同时不必迭代所有键,这是可能的吗?

您可以使用,但对于其中一个方向,它的效率不如普通字典查找

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)`
您可以使用,但对于其中一个方向,它的效率不如普通的字典查找

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)`

混合使用
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

混合使用
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
这是在

答案是一样的-使用
bidict
from

这是在


答案是一样的-使用
bidict
from

dicts不是双向的,所以你要么需要第二个dict,要么需要迭代。没有其他方法。可能的副本不是双向的,所以您需要第二个dict或迭代。没有其他方法。可能的重复我想避免目录中的数据重复。@doorfly,没有数据重复,只是引用重复。我想避免目录中的数据重复。@doorfly,没有数据重复,只是引用重复