Display contents of a Python dictionary in the same order of insertion

1

I am trying to create a dictionary to store the number of incidents that occurred in a month of the year.

It's all right to declare the months and store the data in the dictionary. But when trying to show the data always shows them in an alphabetic way which is not what I want because the logical order of the months can be taken.

Someone has some idea ...

Greetings

    
asked by elMor3no 14.04.2017 в 20:22
source

1 answer

0

A dictionary ( dict ), like the sets ( set ) by definition has no internal order, are implemented by hash tables which allows its efficiency, with respect to ordered objects such as lists, in operations like the search. You can use collections.OrderedDict if you want an object that is as similar as possible to a dictionary but that maintains the order of entry.

Python Dictionary:

d = dict.fromkeys('abcdefghijk')
for k in d.keys():
    print(k)

OrderedDict:

import collections

d = collections.OrderedDict.fromkeys('abcdefghijk')
for k in d.keys():
    print(k) 
    
answered by 14.04.2017 / 20:37
source