Neat way of popping key, value PAIR from dictionary?

后端 未结 3 1366
粉色の甜心
粉色の甜心 2021-01-18 03:20

pop is a great little function that, when used on dictionaries (given a known key) removes the item with that key from the dictionary and also returns the corre

3条回答
  •  情话喂你
    2021-01-18 03:57

    here is a simpler implementation

    class CustomDict(dict):
        def pop_item(self, key):
            popped = {key:self[key]} #save "snapshot" of the value of key before popping
            self.pop(key)
            return popped
    
    a = CustomDict()
    b = {"hello":"wassup", "lol":"meh"}
    a.update(b)
    print(a.pop_item("lol"))
    print(a)
    

    So here we create a custom dict that pops the item you want and gives out the key-value pair

提交回复
热议问题