pythonic way for FIFO order in Dictionary

前端 未结 1 1550
[愿得一人]
[愿得一人] 2021-01-15 11:15

I am trying to populate a dictionary in python but I would like to preserve the order of the keys as they get in - exactly FIFO like a list would do it.

For example,

1条回答
  •  抹茶落季
    2021-01-15 12:09

    Yes. You use a collections.OrderedDict instead of a regular dictionary.

    >>> d = OrderedDict((x,x) for x in reversed(range(10)) )
    >>> d
    OrderedDict([(9, 9), (8, 8), (7, 7), (6, 6), (5, 5), (4, 4), (3, 3), (2, 2), (1, 1), (0, 0)])
    >>> regular = dict((x,x) for x in reversed(range(10)))
    >>> regular
    {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
    

    Notice that the OrderedDict preserves the order whereas the regular dict does not.


    >>> OrderedDict([('dog','dom'),('tiger','EN'), ('panda','EN')])
    OrderedDict([('dog', 'dom'), ('tiger', 'EN'), ('panda', 'EN')])
    

    Another gotcha is that you need to pass items to the constructor (or .update) in a way that preserves order. In other words, you can't pass keyword args to the constructor and expect order to be preserved:

    >>> OrderedDict(dog='dom',tiger='EN',panda='EN')  #doesn't preserve order
    OrderedDict([('tiger', 'EN'), ('panda', 'EN'), ('dog', 'dom')])
    

    0 讨论(0)
提交回复
热议问题