How can I make order to a dictionary? 8/13


I learned that lists can be ordered by .sort.
How can I put order into the dictionary, so it doesn’t start with “orange”?


The simplest way is to keep a sorted list and use it to refer to the dictionary.

>>> fruits_dict = {'orange':5, 'pear':4, 'apple':6, 'banana':8, 'kiwi':3, 'cherry':9}
>>> fruits_index = sorted(fruits_dict.keys());
>>> for fruit in fruits_index:
	print (fruit, fruits_dict[fruit])

('apple', 6)
('banana', 8)
('cherry', 9)
('kiwi', 3)
('orange', 5)
('pear', 4)

Order of displayed totals for 9. Something of Value

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.