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?
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.
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.
Python 3.6 (CPython) As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default.
Dictionaries are not required to keep order. Use OrderedDict
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With