search

Home  >  Q&A  >  body text

python - FIFO OrderedDict的问题

from collections import OrderedDict
import unittest

class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        # print(self)
        if len(self) - containsKey >= self._capacity:
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value)

问题:

del self[key]  有什么特殊用意么,如果key存在的话,直接让它执行OrderedDict.__setitem__()就行了吧,没必要del再重新self[key] = value吧

ps:这是在别人的代码里看到的,欢迎大家指教。

PHP中文网PHP中文网2810 days ago468

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 17:36:30

    Look at the naming of the class. The function of this class should be to ensure that the key-value pair written in the last call is at the end. If you don't del, you just update. When printing, the key-value pair is at the front.

    a = LastUpdatedOrderedDict(256)
    a[3] = 4  
    a[5] = 6
    print a # 按照键值对的插入顺序,打印的是LastUpdatedOrderedDict([(3, 4), (5, 6)])
    a[3] = 2
    print a # 这个时候,又更新了下,以3为key的键值对应该放在后面,打印的是LastUpdatedOrderedDict([(5, 6), (3, 2)])
    
    

    a is an instantiated object with 3 key-value pairs inserted respectively, see
    1) 3 -> 4
    2) 5 -> 6
    3) 3 -> 2
    among them 1) and 3) The keys are the same, but the values ​​are different. The class means who writes the data later. When arranging, who is behind. When completing step 2), the object is LastUpdatedOrderedDict([(3, 4), (5, 6)])
    When performing step 3, because your dictionary is an ordered dictionary and the key-value pair to be inserted later is at the back, the expected result is LastUpdatedOrderedDict([(5, 6), (3, 2 )]).
    If you don’t delete the key here, only the original array will be updated during __setitem__, and the result will be
    LastUpdatedOrderedDict([(3, 2), (5, 6)])
    So you need to delete the key and disrupt it In the previous structure, key-value pairs are inserted.

    reply
    0
  • Cancelreply