I am trying to learn Python from some tutorial. Here is a simple example I encountered that puzzles me.
>>> d={"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> d
{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}
>>> d.keys()
['pwd', 'database', 'uid', 'server']
>>> d.values()
['secret', 'master', 'sa', 'mpilgrim']
As you can see in the first line where I define the dictionary, the item "pwd":"secret"
is the last element in the dictionary. However, when I output the dictionary, it became the first element. And the rest part of the dictionary has been reordered.
May I know why this is happening?
If I use dict.keys() to extract the keys from a dictionary and iterate it in an order that I suppose it to be, will that cause mismatch problem?
If you want to maintain the insertion order, you can use OrderedDict. But regular dict objects store the values by hashing the key and using that for lookups, which doesn't keep the order, but makes lookup faster.