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
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_access.asp
Python - Access Dictionary Items
MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join ยท MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit ... Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary
๐ŸŒ
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.
Discussions

python - Why dict.get(key) instead of dict[key]? - Stack Overflow
It's, in fact, very fast to lookup values using the function induced by dict.get(). The following experiment shows that looking up via the function is over 2 times faster than looking up via the dictionary (it was done on Python 3.9.12). More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way to find a key in a dictionary with only knowing the value?
You will need to iterate: result = [key for key, value in my_dictionary.items() if value == 93] More on reddit.com
๐ŸŒ r/learnpython
11
13
October 28, 2022
What is the most pythonic way of getting an object from a dict when the key may not exist?
You're asking two different questions. What is the most pythonic way of getting an object from a dict when the key may not exist? dict.get(key, default) What is the most pythonic way of doing one thing if a key exists and doing another if it doesn't? if key in dict: # Do the thing else: # Do something else More on reddit.com
๐ŸŒ r/learnpython
16
2
April 15, 2023
Dictionary exercise: Finding a key, given a value
Follow those instructions โ€” iterate over the keys. for key in my_dict: # blah P.S. you canโ€™t return False in the loop, as right now youโ€™d really just be checking if the first key has a value that matches. More on reddit.com
๐ŸŒ r/learnpython
9
7
April 20, 2021
๐ŸŒ
Codecademy
codecademy.com โ€บ learn โ€บ dacp-python-fundamentals โ€บ modules โ€บ dscp-python-dictionaries โ€บ cheatsheet
Python Fundamentals: Python Dictionaries Cheatsheet | Codecademy
Values in a Python dictionary can be accessed by placing the key within square brackets next to the dictionary. Values can be written by placing key within square brackets next to the dictionary and using the assignment operator (=). If the ...
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'
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get a Value from a Dictionary by Key in Python | note.nkmk.me
April 23, 2025 - This article explains how to get a value from a dictionary (dict) by key in Python. Get a value from a dictionary with dict[key] (KeyError for non-existent keys) Use dict.get() to get the default valu ...
Find elsewhere
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python dict and file
Python Dict and File | Python Education | Google for Developers
Python dictionaries, known as "dict", are efficient key/value hash tables represented by key:value pairs within curly braces {}. Values in a dictionary can be accessed or set using square brackets with the key, and "in" or the .get() method ...
๐ŸŒ
Medium
medium.com โ€บ @colinforster_75524 โ€บ stop-using-keys-to-access-dictionary-values-use-the-get-method-instead-c47e087bddf7
Stop Using Keys to Access Dictionary Values. Use the Get Method instead. | by crforster | Medium
January 10, 2024 - We can use a dictionary to store the items as keys and their counts as values, and use the .get method to increment the count of each item by 1, or set it to 1 if it is not in the dictionary. Merge two dictionaries. We can use dictionary comprehension to create a new dictionary that contains the keys and values from both dictionaries and use the .get method to get the value from either dictionary or add them together if they are both present. In conclusion, the .get method is a powerful and handy tool that allows us to work with dictionaries in Python more easily and elegantly.
๐ŸŒ
LaunchCode
education.launchcode.org โ€บ lchs โ€บ appendices โ€บ dictionary-methods โ€บ keys-values-items-examples.html
Return Keys, Values, or Key/Value Pairs โ€” LaunchCode's LCHS documentation
In the dictionary iteration section, we see how to apply the keys() method to loop through a dictionary. ... No arguments are needed inside the parentheses, and the method returns an object that contains all of the values from the dictionary. ... dict_values(['555-5555', '555-5556', '123-456-7890', ...
๐ŸŒ
Pydantic
docs.pydantic.dev โ€บ latest โ€บ concepts โ€บ models
Models | Pydantic Docs
Depending on the types and model configuration involved, the Python and JSON modes may have different validation behavior (e.g. with strictness). If you have data coming from a non-JSON source, but want the same validation behavior and errors youโ€™d get from the JSON mode, our recommendation for now is to either dump your data to JSON (e.g. using json.dumps()), or use model_validate_strings() if the data takes the form of a (potentially nested) dictionary with string keys and values.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-get-dictionary-value-by-key
Get Dictionary Value by Key - Python - GeeksforGeeks
July 23, 2025 - Explanation: d['age'] returns 25 ... since 'country' is not a key in d. ... get() method allows retrieving a value from a dictionary while providing a default value if the key is missing, this prevents KeyError and makes the code ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries.asp
Python Dictionaries
In Python 3.6 and earlier, dictionaries are unordered. Dictionaries are written with curly brackets, and have keys and values: ... Dictionary items are ordered, changeable, and do not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Python_(programming_language)
Python (programming language) - Wikipedia
1 day ago - Python makes a distinction between lists and tuples. Lists are written as [1, 2, 3], are mutable, and cannot be used as the keys of dictionaries (since dictionary keys must be immutable in Python). Tuples, written as (1, 2, 3), are immutable and thus can be used as the keys of dictionaries, ...
๐ŸŒ
CopyAssignment
copyassignment.com โ€บ access-dictionary-values-in-python-dict-key-vs-dict-get-key
Access dictionary values in Python | dict[key] vs dict.get(key) โ€“ CopyAssignment
December 8, 2022 - The second argument of dict.get(key) is the default value and is returned when the key is missing there in the dictionary. If the default is not given, it defaults to None, so that this method never raises a KeyError. my_dict = { 'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4' } print(my_dict) print(my_dict.get('key1')) print(my_dict['key1']) print(my_dict.get('key5', 'some value')) print(my_dict['key5'])
๐ŸŒ
Python Tutor
pythontutor.com โ€บ visualize.html
Python Tutor - Visualize Code Execution
Each Node has a numerical value and a next pointer. (5) See what has been printed up to this step. Here the print statement in the Node constructor (line 5) has run 3 times. The user can navigate forwards and backwards through all execution steps, and the visualization changes to match the run-time state of the stack and heap at each step. In this example, the user would see their custom LinkedList data structure getting incrementally built up one Node at a time via recursive calls to init() until the base case is reached when n==0.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ itertools.html
itertools โ€” Functions creating iterators for efficient looping
The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged.
๐ŸŒ
Daily.dev
app.daily.dev โ€บ home โ€บ stack abuse โ€บ get keys and values from a dictionary in python
Get Keys and Values from a Dictionary in Python | daily.dev
June 7, 2023 - A dictionary in Python is an essential and robust built-in data structure that allows efficient retrieval of data. It is an unordered collection of key-value pairs, where the values are stored under a specific key. In this article, we will take a look at different approaches for accessing keys and values in dictionaries. ... Table of contentsIntroductionA Brief Anatomy of a DictionaryGet Keys in a DictionaryHow to Get Values in a DictionaryGet Key-Value Pairs from a Dictionary Simultaneously
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ dictionary_values.htm
Python dictionary values() Method
When an item is added in the dictionary, the view object also gets updated. In the following example a dictionary 'dict1' is created. This dictionary contains the values: 'Lion' and 'Carnivora'. Thereafter, we append an item in the dictionary which consist of the key 'Kingdom' and its corresponding value 'Animalia'.Then all the values of the dictionary is retrieved using the values() method:
๐ŸŒ
scikit-learn
scikit-learn.org โ€บ stable โ€บ modules โ€บ model_evaluation.html
3.4. Metrics and scoring: quantifying the quality of predictions โ€” scikit-learn 1.9.0 documentation
Note that the dict values can either be scorer functions or one of the predefined metric strings. As a callable that returns a dictionary of scores:
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Set
Set - JavaScript | MDN
1 month ago - Returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is similar to the Map object, so that each entry's key is the same as its value for a Set.