How to show a dictionary’s keys in the order they were inserted

Asked

Viewed 76 times

3

I’m trying to show you keys and its values, but I would like to do so using the predefined order, and not chance.

For example, I have this dictionary:

months = {'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}

But its content is not shown in order, ie first "January" and then "February", etc.

How can I do it?

1 answer

3

Note: since no one answered, I decided to give a personal and formal response.

This problem arises because the standard types Dict in Python are mutable and disorderly, i.e., the initial order of insertion of chaves:valores is not maintained during the life cycle of a dictionary.

One of the best solutions to this problem is to use the class Ordereddict module Collections.

For more documentation and help, see these posts:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.