Accessing items in an collections.OrderedDict by index

后端 未结 9 1602
我寻月下人不归
我寻月下人不归 2020-11-28 19:41

Lets say I have the following code:

import collections
d = collections.OrderedDict()
d[\'foo\'] = \'python\'
d[\'bar\'] = \'spam\'

Is there

9条回答
  •  情话喂你
    2020-11-28 20:29

    It's a new era and with Python 3.6.1 dictionaries now retain their order. These semantics aren't explicit because that would require BDFL approval. But Raymond Hettinger is the next best thing (and funnier) and he makes a pretty strong case that dictionaries will be ordered for a very long time.

    So now it's easy to create slices of a dictionary:

    test_dict = {
                    'first':  1,
                    'second': 2,
                    'third':  3,
                    'fourth': 4
                }
    
    list(test_dict.items())[:2]
    

    Note: Dictonary insertion-order preservation is now official in Python 3.7.

提交回复
热议问题