[Python] Why don’t dictionaries preserve insertion order in Python versions before 3.7?...

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    In Python versions before 3.7, I noticed that dictionaries did not preserve the order of insertion. I thought dictionaries were supposed to maintain the order of keys in the way they were added, but in older versions, this doesn't seem to be the case.

    Example:

    my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict) # In Python 3.6 and earlier, the output order may not be the same as insertion

    Expected output: {'a': 1, 'b': 2, 'c': 3}

    Actual output: {'b': 2, 'a': 1, 'c': 3} # Order can be unpredictable

    I was expecting Python to preserve the insertion order of dictionary keys. I read that this feature was added in Python 3.7, but I want to understand why it wasn’t the case before. Is there any workaround in earlier versions, or is this a core design decision?

    Continue reading...

Compartilhe esta Página