How to print my dictionary in the original order that I configured?
If I have a dictionary like this:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
and I do this:
for cars in smallestCars: print cars
output:
Sentra98 Civic96 Camry98
but i want this:
Civic96 Camry98 Sentra98
Is there a way to print the original dictionary without converting it to a list?
An ordinary dictionary has no order. You need to use the OrderedDict the collections module, which can accept a list of lists or a list of tuples, for example:
OrderedDict
collections
import collections key_value_pairs = [('Civic86', 12.5), ('Camry98', 13.2), ('Sentra98', 13.8)] smallestCars = collections.OrderedDict(key_value_pairs) for car in smallestCars: print(car)
And the result:
Dictionaries are not required to maintain order. Use OrderedDict .
When you create a dictionary, python does not care about the order in which you wrote the elements, and it does not remember the order after creating the object. You cannot expect it (a regular dictionary) to be printed in the same order. Changing the structure of your code is the best option you have, and OrderedDict is a good option, as others claim.
>>> for car in sorted(smallestCars.items(),key=lambda x:x[1]): ... print car[0] ... Civic96 Camry98 Sentra98
You can use a tuple (nested) for this:
smallestCars = [['Civic86', 12.5], ['Camry98', 13.2], ['Sentra98', 13.8]] for car, size in smallestCars: print(car, size) # ('Civic86', 12.5) # ('Camry98', 13.2) # ('Sentra98', 13.8)