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?
In general dictionaries are not sorted. They are grouped by key/value pairs. They are generally fast as they are hash mapped. If you know the key you can quickly get its value.
for example if you wanted to get the value of server one would do this
d['server'] and you would have your answer...
It is because dictionaries are not sorted.You cannot influence the key order in any way. There is Collections.OrderedDict to maintain the insertion order.
Dictionaries are not sorted! Use the Key Value to get the item you want.
It is because of the way dicts are organized internally.
In short, this works via a hash-table which puts the keys into buckets according to their
hash()
value.Depending on how you do it.
should exactly work how you want it to work.
All you have to worry about is, you are getting value corresponding to the key or not and that is guaranteed by
dict
.Output
Note: If you really want the order of the keys to be predictable, set
PYTHONHASHSEED
environmental variable an integer value in the range[0,4294967295]
. Quoting frompython --help
This is because Python's dictionary does not have a predefined order. Think of it as a key-value store. And do not expect an exact ordering of keys and values.
What you can perhaps do, if you need an ordering in a dictionary is to use an
OrderedDict
.