Print original input order of dictionary in python

后端 未结 5 693
你的背包
你的背包 2021-01-11 10:56

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

If I have a dictionary like this:

smallestCars = {\'Civic96\':          


        
相关标签:
5条回答
  • 2021-01-11 11:18

    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
    
    0 讨论(0)
  • 2021-01-11 11:25

    Dictionaries are not required to keep order. Use OrderedDict.

    0 讨论(0)
  • 2021-01-11 11:31

    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.

    0 讨论(0)
  • 2021-01-11 11:38
    >>> for car in sorted(smallestCars.items(),key=lambda x:x[1]):
    ...     print car[0]
    ... 
    Civic96
    Camry98
    Sentra98
    
    0 讨论(0)
  • 2021-01-11 11:42

    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)
    
    0 讨论(0)
提交回复
热议问题