Python: Difference between kwargs.pop() and kwargs.get()

Aliquis picture Aliquis · Mar 11, 2018 · Viewed 32.8k times · Source

I have seen both ways but I do not understand what the difference is and what I should use as "best practice":

def custom_function(**kwargs):
    foo = kwargs.pop('foo')
    bar = kwargs.pop('bar')
    ...

def custom_function2(**kwargs):
    foo = kwargs.get('foo')
    bar = kwargs.get('bar')
    ...

Answer

DhiaTN picture DhiaTN · Mar 11, 2018

get(key[, default]): return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

d = {'a' :1, 'c' :2}
print(d.get('b', 0)) # return 0
print(d.get('c', 0)) # return 2

pop(key[, default]) if key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

d = {'a' :1, 'c' :2}
print(d.pop('c', 0)) # return 2
print(d) # returns {'a': 1}
print(d.get('c', 0)) # return 0

NB: Regarding best practice question, I would say it depends on your use case but I would go by default for .get unless I have a real need to .pop