0

In Python 3.7, dictionaries preserve insertion order. The dict() constructor, when provided with a list of tuples, will insert the keys in order. Will curly brace notation also preserve order? That is, will the below assertion always pass?

import random

keys = [str(i) for i in range(1_000_000)]

test_dict = {key: "" for key in keys}
assert keys == list(test_dict.keys())

I know this seems small, but I'm looking for specific documentation about the curly brace delimiter.

Thanks!

pml
  • 484
  • 3
  • 12
  • 1
    Note that `test_dict = {key: "" for key in keys}` is a dictionary comprehension, not a literal dict constructor. – snakecharmerb Dec 07 '22 at 19:45
  • 2
    Beside the point, but the curly braces aren't operators. I think they're classed as delimiters. – wjandrea Dec 07 '22 at 19:47
  • 2
    The question should not be whether `dict` and `{}` differ. The question should be, "in what order are the keys inserted"? I think you can convince yourself that the keys will be presented in the same order no matter how they are constructed. Even doing them one at a time with a `for` loop will use the same insertion order. – Tim Roberts Dec 07 '22 at 19:54

0 Answers0