Deep LF
Deep LF

Reputation: 199

How the order for dictionary in python is maintained?

>>> dict1 = {'1':'aaa' , '2':'bbb' , '5':'fff' , '10':'zzz'}
>>> dict1
{'1': 'aaa', '10': 'zzz', '2': 'bbb', '5': 'fff'}

>>> dict3 = {'1':'aaa' , '2':'bbb' , '11' : 'hhh' , '5':'fff' , '7' : 'ggg' , '10':'zzz'}
>>> dict3
{'11': 'hhh', '10': 'zzz', '1': 'aaa', '2': 'bbb', '5': 'fff', '7': 'ggg'}

In what manner/algorithm, the dictionary is maintaining the sorting of keys/values, BY DEFAULT??

Upvotes: 0

Views: 90

Answers (1)

Wooble
Wooble

Reputation: 89887

Python dictionaries are not ordered. You can use collections.OrderedDict for a dict-like object that is ordered by insertion order.

When you print a dict or iterate through the keys, the output is in an arbitrary order that's stable as long as the dictionary isn't changed.

Upvotes: 2

Related Questions