Python并没有明显的方式从字典中获取特定的元素 [英] Python and no obvious way to get a specific element from a dictionary

查看:147
本文介绍了Python并没有明显的方式从字典中获取特定的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以轻松地在Python中进行循环,以循环遍历字典的所有元素,并按照我附加元素的顺序进行循环访问,但是没有明显的方法访问特定的元素?当我说元素时,我正在谈论一个关键的+值对。

How come that I can easily do a for-loop in Python to loop through all the elements of a dictionary in the order I appended the elements but there's no obvious way to access a specific element? When I say element I'm talking about a key+value pair.

我已经看过Python上的一些基础教程在字典上的描述,但没有一个答案我的问题,我在docs.python.org中找不到我的答案。

I've looked through what some basic tutorials on Python says on dictionaries but not a single one answers my question, I can't find my answer in docs.python.org either.

根据:
(Senderies comment)一个dict应该是无序的,但是为什么这个for循环打印他们按照我把它们放在的顺序?

According to: accessing specific elements from python dictionary (Senderies comment) a dict is supposed to be unordered but then why does the for-loop print them in the order I put them in?

推荐答案

您可以通过键访问字典中的特定元素。 em>这是一个字典如果这个行为不是你想要的,使用除字典之外的东西。

You access a specific element in a dictionary by key. That's what a dictionary is. If that behavior isn't what you want, use something other than a dictionary.

$ b $一个dict应该是无序的,但是为什么这个for循环按照我把它们的顺序打印出来?

a dict is supposed to be unordered but then why does the for-loop print them in the order I put them in?

一致:bas你根本就把Python放在Python里面。这不是太难做,特别是整数( int s是他们自己的哈希值,并且倾向于以数字顺序从字母出来,尽管这是一个CPython的实现细节,并且在其他Python实现中可能不是这样),特别是如果以数字顺序将它们开头。

Coincidence: basically, you happened to put them in in the order that Python prefers. This isn't too hard to do, especially with integers (ints are their own hashes and will tend to come out from a dict in ascending numeric order, though this is an implementation detail of CPython and may not be true in other Python implementations), and especially if you put them in in numerical order to begin with.

无序真的意味着你不能控制顺序,并且可能会因为各种实现特定的标准而改变,所以你不应该依赖它。当然,当你遍历一个字典时,元素会出现在一些顺序。

"Unordered" really means that you don't control the order, and it may change due to various implementation-specific criteria, so you should not rely on it. Of course when you iterate over a dictionary elements come out in some order.

如果你需要能够通过数字索引来访问字典元素有很多方法可以做到这一点。 collections.OrderedDict 是标准的方式;钥匙总是按你添加的顺序返回,所以你可以随时执行 foo [foo.keys()[i]] 访问 th元素。还有其他可以使用的方案。

If you need to be able to access dictionary elements by numeric index, there are lots of ways to do that. collections.OrderedDict is the standard way; the keys are always returned in the order you added them, so you can always do foo[foo.keys()[i]] to access the ith element. There are other schemes you could use as well.

这篇关于Python并没有明显的方式从字典中获取特定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆