Possible Duplicate:
Why is python ordering my dictionary like so?
I am a bit confused with the output I get from the following. I do not understand the order of the loop that is executed.
domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
"us": "United States", "no": "Norway" }
for key in domains:
print key
Output here is
sk
de
no
us
hu
but not
de
sk
hu
us
no
similarly, here
num = {1:"one",4:"two",23:"three",10:"four"}
for key in num:
print key
output is
1
10
4
23
but not
1
4
23
10
Thanks for helping
Yes, it should, every time, since lists are ordered. If you are iterating over a dict , the order may be different than expected. Python dicts are unordered.
So first the condition is checked, then the loop body is executed, then the increment.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.
Python dictionaries do not preserve ordering:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions
A dictionary in CPython is implemented as a hash table to enable fast lookups and membership tests, and enumerating the keys or values happens in the order the items are listed in that table; where they are inserted depends on the hash value for the key and if anything was hashed to the same slot before already.
You'll have to either sort the keys every time when displaying or use a a different type of data structure to preserve ordering. Python 2.7 or newer has a collections.OrderedDict()
type, or you can use a list of two-value tuples (at which point lookups of individual key-value pairs is going to be slow).
The order is unspecified. It is, however, guaranteed to remain unchanged in the absence of modifications to the dictionary.
You can sort the keys when iterating:
for key in sorted(domains):
print key
Finally, it may be useful to note that newer versions of Python have collections.OrderedDict
, which preserves the insertion order.
Python dictionaries don't have an order. However, you can specify an order by using the sorted(domains)
function. By default, it sorts using the key.
for key in sorted(domains):
print key
will produce
de
hu
no
sk
us
If you want to order based on values, you can use something like sorted(domains.items(), key = lambda(k, v): (v, k))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With