Search code examples
pythonlistpython-2.7dictionaryprinting

Print original input order of dictionary in python


How do I print out my dictionary in the original order I had set up?

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

it outputs:

Sentra98
Civic96
Camry98

but what I want is this:

Civic96
Camry98
Sentra98

Is there a way to print the original dictionary in order without converting it to a list?


Solution

  • A regular dictionary doesn't have order. You need to use the OrderedDict of the collections module, which can take a list of lists or a list of tuples, just like this:

    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 output is:

    Civic96
    Camry98
    Sentra98