检查字典索引是否与该索引处存储的值相同python

发布于 2025-01-10 07:24:32 字数 217 浏览 3 评论 0原文

我如何检查字典索引是否与Python中该索引中存储的值相同

例如,

my_dictionary = {3:3, 5:4, 6:2, 10:0, 19:1}

:显然我们可以看到在第二个索引处存储的值是2; 这里我们必须返回 True 但首先索引的值为 3; 这里我们必须返回 False

最终结果应该如下所示: {假,假,真,假}

How can i check if the dictionary index is same as the value stored in that index in python

for example:

my_dictionary = {3:3, 5:4, 6:2, 10:0, 19:1}

clearly we can see that at 2nd index the value stored is 2;
here we have to return True
but at first index we have the value 3;
here we have to return False

the final result should look like this:
{False , False, True, False}

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

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

发布评论

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

评论(1

梦里的微风 2025-01-17 07:24:32

对字典的使用enumerate并进行比较:

>>> my_dictionary = {3: 3,    5: 4,    6: 2,    10: 0,    19: 1}
>>> [i == v for i, v in enumerate(my_dictionary.values())]
[False, False, True, False, False]

请注意,字典排序有点棘手,并且不是您通常想要编码或过于依赖的东西。在最新版本的 Python 中,字典根据添加键的时间保留排序,但您无法像对列表那样对字典进行排序,并且在旧版本的 Python 中,字典被认为是完全无序的。

考虑使用 OrderedDict 甚至元组列表来存储此数据。

Use enumerate over the dictionary's values and compare:

>>> my_dictionary = {3: 3,    5: 4,    6: 2,    10: 0,    19: 1}
>>> [i == v for i, v in enumerate(my_dictionary.values())]
[False, False, True, False, False]

Note that dictionary ordering is a little tricky and is not something that you usually want to code around or depend on too strongly. In recent versions of Python, dictionaries preserve ordering according to when their keys were added, but you can't sort a dictionary like you can a list, and in older versions of Python dictionaries were considered completely unordered.

Consider using an OrderedDict or even a list of tuples to store this data instead.

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