The keys() method of a dictionary object returns a list of all the
keys used in the dictionary, in arbitrary order (if you want it
sorted, just apply the sorted() function to it). To check whether a
single key is in the dictionary, use the in keyword.
The order of keys in a dict()
is not defined (it depends on which implementation of Python you're using). In order to iterate through dict in an ordered fashion:
my_dict = {'a': 10, 'b': 20, 'c': 30}
for key in sorted(my_dict.keys()):
print key, my_dict[key]
This will give you the right order:
a 10
b 20
c 30
The reason why keys are not sorted is that dict()
uses hash table to store them, that is also why you can only have one unique key and why you can have composite keys that are composed of hashable objects. The keys are sorted by their hash, for a more in-depth explanation see this SO question