OrderedDict for older versions of python

前端 未结 7 2135
春和景丽
春和景丽 2020-11-27 17:59

Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from 3.1 and 2.7. How can I use an ordered dictionary

7条回答
  •  心在旅途
    2020-11-27 18:23

    To import a OrderedDict class for different versions of Python, consider this snippet:

    try:
        from collections import OrderedDict
    except ImportError:
        from ordereddict import OrderedDict
    
    # Now use it from any version of Python
    mydict = OrderedDict()
    

    Versions older than Python 2.6 will need to install ordereddict (using pip or other methods), but newer versions will import from the built-in collections module.

提交回复
热议问题