Print original input order of dictionary in python
Asked Answered
T

6

15

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?

Tasker answered 21/11, 2013 at 1:19 Comment(2)
Thats hashing :) not sorted in any orderRexferd
But why the order changed when printing it, Why it is not printing as assignedGeosyncline
B
21

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
Buffet answered 21/11, 2013 at 1:23 Comment(0)
H
2

Dictionaries are not required to keep order. Use OrderedDict.

Hellish answered 21/11, 2013 at 1:23 Comment(0)
L
2
>>> for car in sorted(smallestCars.items(),key=lambda x:x[1]):
...     print car[0]
... 
Civic96
Camry98
Sentra98
Lustrous answered 21/11, 2013 at 3:15 Comment(0)
C
1

When you create the dictionary, python doesn't care about in what order you wrote the elements and it won't remember the order after the object is created. You cannot expect it(regular dictionary) to print in the same order. Changing the structure of your code is the best option you have here and the OrderedDict is a good option as others stated.

Canice answered 21/11, 2013 at 1:32 Comment(0)
G
0

You can use a tuple (nested) array to do 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)
Gherlein answered 16/1, 2018 at 17:51 Comment(0)
F
0

The order of printing of a dictionary in Python depends on the version you're using: Python 3.7 and above:

Dictionaries are ordered. This means that they will print in the order in which the key-value pairs were inserted.

Python 3.6 and below: Dictionaries are unordered. This means that the printing order is arbitrary and not guaranteed to be the same as the insertion order.

Fondafondant answered 1/8, 2024 at 14:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.