Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unordered dict in python 3.7

Dictionaries in python are ordered since Python 3.6

From - https://stackoverflow.com/a/39980744/4647107

Are dictionaries ordered in Python 3.6+?

They are insertion ordered. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.

Is there a way to implement an unordered dictionary in python now?

like image 506
Pratyush Das Avatar asked Jul 25 '26 13:07

Pratyush Das


1 Answers

You can fake it:

>>> import random
>>> d={'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}
>>> items=list(d.items())
>>> random.shuffle(items)
>>> dict(items)
{'c': [7, 8, 9], 'b': [4, 5, 6], 'a': [1, 2, 3]}
>>> 
like image 151
U12-Forward Avatar answered Jul 28 '26 01:07

U12-Forward