It allows you to provide a default value if the key is missing:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas

dictionary["bogus"]

would raise a KeyError.

If omitted, default_value is None, such that

dictionary.get("bogus")  # <-- No default specified -- defaults to None

returns None just like

dictionary.get("bogus", None)

would.

Answer from unutbu on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-dict-get-value-by-key-default
Python Dict Get Value by Key Default - GeeksforGeeks
July 23, 2025 - If the key exists then it adds the corresponding value. If the key is missing, it assigns the default value 'Unknown'. This method is useful for creating a new dictionary with a specified set of keys and default values.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get a Value from a Dictionary by Key in Python | note.nkmk.me
April 23, 2025 - Otherwise, None is returned. d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'} print(d.get('key1')) # val1 print(d.get('key4')) # None ... You can provide a default value as the second argument, which will be returned if the key is not found.
Discussions

Get dict value by key, default if doesn't exist or val is None
Something like this? x = { 'a': 1, 'c': None } x.get('b') or 2 # b = 2 x.get('c') or 3 # c = 3 More on reddit.com
๐ŸŒ r/learnpython
15
6
August 4, 2019
How to get key values from default dictionary in Python? - Stack Overflow
I have a default dictionary with name df: defaultdict( , {u'DE': 1, u'WV': 1, u'HI': 1, u'WY': 1, u'NH': 2, u'NJ': 1, u'NM': 1, u'TX': 1, u'LA': 1, u'NC': 1, u'NE': 1, u'TN': 1, u... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Why are there two ways to retrieve values from a dictionary in Python? - Software Engineering Stack Exchange
In Python there are basically two ways to get a value from a dictionary: dictionary["key"] dictionary.get("key") Is there any - maybe historical - reason for this behavior? I More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
January 15, 2024
python - Return a default value if a dictionary key is not available - Stack Overflow
I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called "token" and my key that I am looking for is "error". I am looking for key "error" and if it was not there setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement would handle if I do have the key "error". Copyif ((token.get... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 16
1712

It allows you to provide a default value if the key is missing:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas

dictionary["bogus"]

would raise a KeyError.

If omitted, default_value is None, such that

dictionary.get("bogus")  # <-- No default specified -- defaults to None

returns None just like

dictionary.get("bogus", None)

would.

2 of 16
244

What is the dict.get() method?

As already mentioned the get method contains an additional parameter which indicates the missing value. From the documentation

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.

An example can be

>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1

Are there speed improvements anywhere?

As mentioned here,

It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.

Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)

def getway(d):
    for i in range(100):
        s = d.get(i)

def lookup(d):
    for i in range(100):
        s = d[i]

Now timing these two functions using timeit

>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979

As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis

>>> def lookup(d,val):
...     return d[val]
... 
>>> def getway(d,val):
...     return d.get(val)
... 
>>> dis.dis(getway)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_ATTR                0 (get)
              6 LOAD_FAST                1 (val)
              9 CALL_FUNCTION            1
             12 RETURN_VALUE        
>>> dis.dis(lookup)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (val)
              6 BINARY_SUBSCR       
              7 RETURN_VALUE  

Where will it be useful?

It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces

 if key in dic:
      val = dic[key]
 else:
      val = def_val

To a single line, val = dic.get(key,def_val)

Where will it be NOT useful?

Whenever you want to return a KeyError stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!

Is it possible to have get like feature in dict['key']?

Yes! We need to implement the __missing__ in a dict subclass.

A sample program can be

class MyDict(dict):
    def __missing__(self, key):
        return None

A small demonstration can be

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ default-dictionary-values
Setting default dictionary values in Python - Python Morsels
February 13, 2026 - In that case, you could use the collections.defaultdict class. This class accepts a callable to use as the factory function for the value of each missing key lookup. Passing list will create a defaultdict that defaults the value for each missing ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-get-dictionary-value-by-key
Get Dictionary Value by Key - Python - GeeksforGeeks
July 23, 2025 - defaultdict class from the collections module is an advanced dictionary type that provides a default value when a missing key is accessed, this prevents KeyError and is useful when handling multiple missing keys efficiently.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ get dict value by key, default if doesn't exist or val is none
r/learnpython on Reddit: Get dict value by key, default if doesn't exist or val is None
August 4, 2019 -

Good day,

is there a way to get dictionary value or default if key doesn't exist OR value is None?

e.g.

x = { 'a': 1, 'c': None }

x.get('b', 2) # I want b = 2, I have it  
x.get('c', 3) # I want c = 3, but key 'c' exists, so I get c = None

I can of course create own dict object and override "get" or implement additional method, but maybe there's a fancy standard way?

p.s. simple practical example "for what":

You need to parse YAML file, there's array key "items":

items:
 - 1
 - 2
 - 3

If key is empty, any YAML parser set it to "None", however it's much better to have an empty list instead.

Find elsewhere
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ dictionary_get.htm
Python dictionary get() Method
Following is the syntax of the Python dictionary get() method โˆ’ ... value (optional) โˆ’ This is the Value to be returned in case the specified key does not exists. It's default value is None.
๐ŸŒ
Quantifiedcode
docs.quantifiedcode.com โ€บ python-anti-patterns โ€บ correctness โ€บ not_using_get_to_return_a_default_value_from_a_dictionary.html
Not using get() to return a default value from a dict โ€” Python Anti-Patterns documentation
While there is nothing wrong this, it is more concise to use the built-in method dict.get(key[, default]) from the Python Standard Library. If the key exists in the dict, then the value for that key is returned. If it does not exist, then the default value specified as the second argument to ...
๐ŸŒ
dbader.org
dbader.org โ€บ blog โ€บ python-dict-get-default-value
Using get() to return a default value from a Python dict โ€“ dbader.org
September 14, 2016 - def greeting(userid): try: return "Hi %s!" % name_for_userid[userid] except KeyError: return "Hi there" Again, this implementation would be correct โ€“ but we can come up with a cleaner solution still! Pythonโ€™s dictionaries have a get() method on them which supports a default argument that can be used as a fallback value:
๐ŸŒ
Learn By Example
learnbyexample.org โ€บ python-dictionary-get-method
Python Dictionary get() Method - Learn By Example
April 20, 2020 - The get() method returns the value for key if key is in the dictionary, else default. If default is not specified, it returns None.
๐ŸŒ
Real Python
realpython.com โ€บ python-defaultdict
Using the Python defaultdict Type for Handling Missing Keys โ€“ Real Python
July 31, 2023 - If you try to get access to a key with a subscription operation, like dd_one['missing'], then .__getitem__() is automatically called by Python. If the key is not in the dictionary, then .__missing__() is called, which generates a default value by calling .default_factory().
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-dictionary-get-method
Python Dictionary get() Method - GeeksforGeeks
April 18, 2026 - The dict.get() method in Python returns the value associated with a given key. If the key is not present, it returns None by default or a specified default value if provided. It allows safe access to dictionary keys without raising a KeyError.
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ python โ€บ python dictionary get: step-by-step guide
Python Dictionary Get: Step-By-Step Guide | Career Karma
December 1, 2023 - The Python dictionary get() method returns the value associated with a specific key. get() accepts two arguments: the key for which you want to search and a default value that is returned if the key is not found.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ does dict.get() always try to resolve the default value?
r/learnpython on Reddit: does dict.get() always try to resolve the default value?
February 18, 2022 -

I had this dict

d = {"a": 1, "b": 2, "c": 3}

and my program would access the dict either by a key I knew was present, or by a string number, eg "1". If the key wasn't present, I wanted the method to return the key as an int (I knew that if it wasn't present it would always be a number). Basically I wanted this functionality:

d.get("a") # -> 1
d.get("9") # -> 9

So I thought I could write

k = "a"
d.get(k, int(k))
# ValueError: invalid literal for int() with base 10: 'k'

so even though "a" is a key in the dictionary, d.get() tries to parse int("a"). Intuitively it feels like it doesn't have to, because here the default value isn't needed.

Is there a reason for this? Just asking out of curiosity. I know there are workarounds, try statements and so on, but they are more verbose, and want to know if I'm missing something basic here..

๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ standard-library โ€บ dict โ€บ get
Python dict get() - Retrieve Element Value | Vultr Docs
November 8, 2024 - Expand your understanding of this ... gracefully. Acces a dictionary by specifying the key. Assign a default value that get() should return if the key does not exist....
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python dictionary get
How to Get Dictionary Value in Python | Delft Stack
March 11, 2025 - What is the difference between ... sets it to a default if it doesnโ€™t exist, while get() only retrieves the value and can return a default without modifying the dictionary....
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get Keys from a Dictionary by Value in Python | note.nkmk.me
May 19, 2025 - Iterate Over Dictionary Keys, Values, and Items in Python ยท d = {'key1': 1, 'key2': 2, 'key3': 3} print(list(d)) # ['key1', 'key2', 'key3'] ... You can get dictionary keys based on their values using a list comprehension with the items() method.