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.
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.
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?
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.
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.
If you need to be able to access dictionary elements by numeric index, there are lots of ways to do that.
collections.OrderedDictis the standard way; the keys are always returned in the order you added them, so you can always dofoo[foo.keys()[i]]to access theith element. There are other schemes you could use as well.