1

I'm learning python syntax about list comprehension my purpose is using list comprehension get dic keys and create new set data. Here is my code.

    dic = {'hello': 2, 'hiaaaa': 1, 'goodmorning': 0}

    new_set = { len(name) for name in dic.keys() }

    print(new_set)

I expected the result is {5, 6, 11}not {11, 5, 6}.

When I add data to dic the result is always different. Sometimes dic is ordered, sometimes dic is disordered. So does python list comprehension have any special rules? Or is it a complex bug?

cokeman19
  • 2,405
  • 1
  • 25
  • 40
manngold
  • 13
  • 2

1 Answers1

0

A set is unordered in Python. To preserve order, you can consider using an OrderedDict from the collections module.

dict objects didn't use to preserve order, but this behaviour is guaranteed after Python 3.7. OrderedDicts still have some advantages under the hood to be optimized for tracking insertion order, however.

CDJB
  • 14,043
  • 5
  • 29
  • 55