Python tip: default when fetching a dictionary key value.

Today I Learned that when fetching a value from a Python dictionary, you can set a default!

A trivial example:

def build(**kwargs):
    source = kwargs.get("source", "git")

That’s pretty neat! Seems like some other dict methods have this signature too.

Ivan Sagalaev adds:

You can also take out that key and value from the dict if you’re using .pop() instead of .get().

For example, it’s often useful when you work with kwargs and want to look at the keys you care about and pass the rest to another function call you’re wrapping.



Comment via email.