Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 721
user2989027 Avatar asked Nov 21 '13 01:11

user2989027


People also ask

What is the order of dictionary in Python?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

How are dictionary entries in Python ordered?

A dictionary in Python is a collection of items that stores data as key-value pairs. In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.

Is Python dict Keys ordered?

Python 3.6 (CPython) As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default.


2 Answers

Dictionaries are not required to keep order. Use OrderedDict.

like image 37
Amadan Avatar answered Oct 24 '22 10:10

Amadan


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
like image 96
Peter Varo Avatar answered Oct 24 '22 09:10

Peter Varo