Code:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
This prints ['a', 'c', 'b']
. I'm unsure of how the method keys()
determines the order of the keywords within l. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b', 'c']
.
This question is related to
python
dictionary
Just sort the list when you want to use it.
l = sorted(d.keys())
>>> print sorted(d.keys())
['a', 'b', 'c']
Use the sorted function, which sorts the iterable passed in.
The .keys()
method returns the keys in an arbitrary order.
In Python 3.7.0 the insertion-order preservation nature of dict
objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.
As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python.
Use the collections.OrderedDict
class when you need a dict
that
remembers the order of items inserted.
Although the order does not matter as the dictionary is hashmap. It depends on the order how it is pushed in:
s = 'abbc'
a = 'cbab'
def load_dict(s):
dict_tmp = {}
for ch in s:
if ch in dict_tmp.keys():
dict_tmp[ch]+=1
else:
dict_tmp[ch] = 1
return dict_tmp
dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))
output:
for string abbc, the keys are dict_keys(['a', 'b', 'c'])
for string cbab, the keys are dict_keys(['c', 'b', 'a'])
From http://docs.python.org/tutorial/datastructures.html:
"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)."
Source: Stackoverflow.com