如何在Python中存储键值和值键?

发布于 2024-11-09 07:12:17 字数 322 浏览 3 评论 0原文

我有一个存储成对数据的有点大的数据结构。单个数据很小并且很容易散列,并且其中有大约数十万个数据点。

起初,这是一个只能通过键访问的简单字典。然而后来我发现我还需要按值访问它,即获取某个值的密钥。由于这样做的频率比通过密钥访问要少一些(~1/10),所以我通过简单地迭代所有字典 items() 来简单地实现它。事实证明,每秒几十万次调用有点缓慢。它大约慢了500倍。

所以我的下一个想法是也使用保存反向字典。然而,这似乎是一个相当不优雅的解决方案,所以我向你们寻求帮助。

你知道 Python 中存储数据对的数据结构可以通过数据对中的任意一个数据点访问吗?

I have this somewhat big data structure that stores pairs of data. The individual data is tiny and readily hashable, and there are something like a few hundred thousand data points in there.

At first, this was a simple dict that was accessed only by keys. Later on however, I discovered that I also needed to access it by value, that is, get the key for a certain value. Since this was done somewhat less often (~1/10) than access by key, I naïvely implemented it by simply iterating over all the dicts items(). Which proved a bit sluggish at a few hundred thousand calls per second. It is about 500 times slower.

So my next idea was to just use save the reverse dict, too. This seems to be a rather inelegant solution however, so I turn to you guys for help.

Do you know any data structure in Python that stores data pairs that can be accessed by either data point of the pair?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

○愚か者の日 2024-11-16 07:12:17

您可以尝试 bidict

You could try bidict.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文