You could use get twice:

example_dict.get('key1', {}).get('key2')

This will return None if either key1 or key2 does not exist.

Note that this could still raise an AttributeError if example_dict['key1'] exists but is not a dict (or a dict-like object with a get method). The try..except code you posted would raise a TypeError instead if example_dict['key1'] is unsubscriptable.

Another difference is that the try...except short-circuits immediately after the first missing key. The chain of get calls does not.


If you wish to preserve the syntax, example_dict['key1']['key2'] but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:

class Hasher(dict):
    # https://stackoverflow.com/a/3405143/190597
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>

Note that this returns an empty Hasher when a key is missing.

Since Hasher is a subclass of dict you can use a Hasher in much the same way you could use a dict. All the same methods and syntax is available, Hashers just treat missing keys differently.

You can convert a regular dict into a Hasher like this:

hasher = Hasher(example_dict)

and convert a Hasher to a regular dict just as easily:

regular_dict = dict(hasher)

Another alternative is to hide the ugliness in a helper function:

def safeget(dct, *keys):
    for key in keys:
        try:
            dct = dct[key]
        except KeyError:
            return None
    return dct

So the rest of your code can stay relatively readable:

safeget(example_dict, 'key1', 'key2')
Answer from unutbu on Stack Overflow
Top answer
1 of 16
583

You could use get twice:

example_dict.get('key1', {}).get('key2')

This will return None if either key1 or key2 does not exist.

Note that this could still raise an AttributeError if example_dict['key1'] exists but is not a dict (or a dict-like object with a get method). The try..except code you posted would raise a TypeError instead if example_dict['key1'] is unsubscriptable.

Another difference is that the try...except short-circuits immediately after the first missing key. The chain of get calls does not.


If you wish to preserve the syntax, example_dict['key1']['key2'] but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:

class Hasher(dict):
    # https://stackoverflow.com/a/3405143/190597
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>

Note that this returns an empty Hasher when a key is missing.

Since Hasher is a subclass of dict you can use a Hasher in much the same way you could use a dict. All the same methods and syntax is available, Hashers just treat missing keys differently.

You can convert a regular dict into a Hasher like this:

hasher = Hasher(example_dict)

and convert a Hasher to a regular dict just as easily:

regular_dict = dict(hasher)

Another alternative is to hide the ugliness in a helper function:

def safeget(dct, *keys):
    for key in keys:
        try:
            dct = dct[key]
        except KeyError:
            return None
    return dct

So the rest of your code can stay relatively readable:

safeget(example_dict, 'key1', 'key2')
2 of 16
94

By combining all of these answer here and small changes that I made, I think this function would be useful. its safe, quick, easily maintainable.

def deep_get(dictionary, keys, default=None):
    return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)

Example :

from functools import reduce
def deep_get(dictionary, keys, default=None):
    return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)

person = {'person':{'name':{'first':'John'}}}
print(deep_get(person, "person.name.first"))    # John

print(deep_get(person, "person.name.lastname")) # None

print(deep_get(person, "person.name.lastname", default="No lastname"))  # No lastname
🌐
Reddit
reddit.com › r/learnpython › using get() with nested dictionary.
r/learnpython on Reddit: Using get() with nested dictionary.
April 10, 2024 -

Hey all, hoping someone can help me out. I'm new to python but getting the hang of it. I'm using subprocess to run ffprobe and have it return JSON. Depending on the file I'm analyzing, some properties may not exist and won't appear in the JSON results. If i print this it works:

dvd_properties['streams'][0]['duration']

But I'm having trouble using the get() method on it:

dvd_properties.get('streams').get('0').get('duration'), "Unknown"

I'm trying to use get() so I have a default value if there are no results in the JSON output. I'm testing on a file that does have the duration element to make sure it works if I have data.

Can anyone lend me a hand? I've tried to search but I can't find anything about this particular situation. I have the get('parent').get('child') working for simple cases, so I'm hoping it will work here as well and I'm just missing something obvious.

Thanks in advance, I do appreciate it.

Discussions

Accessing first 10 key-value pairs in nested dictionary, creating a new nested dictionary with them.
Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today. Start your free trial ... I am at the end of a long data science assignment using python/pandas. My last step is to take a nested dictionary of the words spoken by the 4 major ... More on teamtreehouse.com
🌐 teamtreehouse.com
6
April 11, 2021
python - Getting a key's value in a nested dictionary - Code Review Stack Exchange
I just found a now deleted question on Stack Overflow and solved the problem. The OP was asking for a way to get all the values contained by all 'PLU' keys. I solved it this way but because I am a ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 15, 2018
Dict built-in get/set methods for nested keys - Ideas - Discussions on Python.org
apparently, there is no built-in dict method (let’s call it .nestkey) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures, e.g., dic_1.nestkey(list… More on discuss.python.org
🌐 discuss.python.org
0
September 21, 2024
python - Accessing value inside nested dictionaries - Stack Overflow
There are realistic scenarios where ... deeply) nested dictionary where it would be cumbersome to call get() or the [] operator on every intermediate dict. 2018-12-05T15:19:58.607Z+00:00 ... You however can't alias an alias, so if you are planning to do the process more than once in a recursive manner, you gotta have the keys, or else it's gonna pass by value the second ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › accessing-value-inside-python-nested-dictionaries
Python - Accessing Nested Dictionaries - GeeksforGeeks
July 23, 2025 - Python · nd = { "fruit": { "apple": { "color": "red" }}} # Accessing the value color = nd["fruit"]["apple"]["color"] print(color) Output · red · In this example, values in the nested market dictionary are accessed using get() method.
🌐
Team Treehouse
teamtreehouse.com › community › accessing-first-10-keyvalue-pairs-in-nested-dictionary-creating-a-new-nested-dictionary-with-them
Accessing first 10 key-value pairs in nested dictionary, creating a new nested dictionary with them. (Example) | Treehouse Community
April 11, 2021 - It's close enough and I have a week to figure out how to make the tuples into key-value pairs. It does what was asked, though, those tuples are the 10 most common words spoken by the characters and the count for those (minus stop words) Thank you for responding to me. I appreciated your time. ... See dict() in docs for various ways to make a new dict from other data. ... the point was (as I understood it) to take 2 columns of a dataframe (characters and their lines), and create a nested dictionary of the 4 main characters and the top ten words that they spoke (removing the stop words).
🌐
W3Schools
w3schools.com › python › python_dictionaries_nested.asp
Python - Nested Dictionaries
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... A dictionary can contain dictionaries, this is called nested dictionaries.
Top answer
1 of 4
10

Great job so far! I have a few suggestions for your code:

  1. Avoid writing functions with side effects such as printed output. Side effects make a function much less reusable. Instead, you may return a generator that yields the next entry. This gives the caller maximum control over what to do with the result set: print it, iterate one by one, just get the first few items without searching the entire structure, etc.

  2. Consider adhering more strictly to Python naming conventions. For example, functions should be lower_camel_cased. Since your function returns multiple PLUs, the function name seems more accurately written as get_plus. You can remove the pass keyword in your function and pay close attention to spacing, for example in the print (data[item]) function call and your else : block.

  3. Clean up lines like

    else :
        if item == 'PLU':
            print (data[item])
    

    Which is logically equivalent to:

    elif item == 'PLU':
        print(data[item])
    
  4. Use data.items() to iterate through your dictionary's keys and values rather than only keys. This allows cleaner syntax to access values.

  5. Make your function more general for maximum reusability. Fetching a list of values by key from a dictionary is a task that should work for any key. Why not make "PLU" a search parameter? If you want to keep the original get_plus version, write both functions and have get_plus wrap the generalized version.

  6. isinstance may be a more accurate choice than type if you wish to allow collection subclasses of dictionary to use your function.

Here's my version for consideration:

def find_by_key(data, target):
    for key, value in data.items():
        if isinstance(value, dict):
            yield from find_by_key(value, target)
        elif key == target:
            yield value


def main():
    menu = {
      'PLU' : '234',
      'Salad': {
        'salad': {
            'ceaser':{
                'PLU': '32'
            },
            'italian':{
                'PLU': '33'
            }
        }
      },
      'Dessert': {
        'cookie': {
          'PLU': '334',
          'NAME': 'cookie ',
        }
      },
      'Appetizer': {
        'extra sauce': {
          'PLU': '61',
          'NAME': 'extra sauce',
        }
      }
    }

    for x in find_by_key(menu, "PLU"):
        print(x)


if __name__ == '__main__':
    main()
2 of 4
6

Your code is well organized and read well but there are a few oddities:

  1. Read PEP8 and apply official coding conventions so that your code read like Python code;
  2. Remove that useless pass;
  3. Don't print your results in the function that compute them, instead return them to the caller so your function is reusable (in your case, yielding them might be more appropriate);
  4. Don't check for a specific type using type: favor isinstance; better would be to not check for a type at all but for a feature: call the items method of what would appear to be a dict and work with that, discard anything else that raise an AttributeError;
  5. A more generic function would accept the key to search for as parameter;
  6. A recursive approach cannot handle arbitrary large structures due to the recursion limit, an iterative approach can (even though it would rarely be an issue in practice).

Proposed improvements:

def retrieve_nested_value(mapping, key_of_interest):
    mappings = [mapping]
    while mappings:
        mapping = mappings.pop()
        try:
            items = mapping.items()
        except AttributeError:
            # we didn't store a mapping earlier on so just skip that value
            continue

        for key, value in items:
            if key == key_of_interest:
                yield value
            else:
                # type of the value will be checked in the next loop
                mappings.append(value)


def main():
    menu = {...}
    for plu in retrieve_nested_value(menu, 'PLU'):
        print(plu)


if __name__ == '__main__':
    main()
Find elsewhere
🌐
GitHub
gist.github.com › PatrikHlobil › 9d045e43fe44df2d5fd8b570f9fd78cc
Get all keys or values of a nested dictionary or list in Python · GitHub
def get_keys(dictionary): result = [] for key, value in dictionary.items(): if type(value) is dict: new_keys = get_keys(value) result.append(key) for innerkey in new_keys: result.append(f'{key}/{innerkey}') else: result.append(key) return result ...
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
In the above program, the first loop returns all the keys in the nested dictionary people. It consist of the IDs p_id of each person. We use these IDs to unpack the information p_info of each person. The second loop goes through the information of each person. Then, it returns all of the keys name, age, sex of each person's dictionary. Now, we print the key of the person’s information and the value for that key.
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - Nested dictionaries are essential ... data in Python. They’re particularly useful for working with JSON data, configuration settings, or any structured data that has multiple levels. A nested dictionary is simply a dictionary that contains other dictionaries as values...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-get-all-values-from-nested-dictionary
Python Get All Values from Nested Dictionary - GeeksforGeeks
July 24, 2025 - In this approach, we are using the recursive function apporach1Fn to traverse over the nested input dictionary, we are extracting all values including the nested dictionaries and lists. Then, we store the result in the output object and print it using the print method in Python. Example: In this example, we are using the Recursive Method to Get All Values from Nested Dictionary.
🌐
Python.org
discuss.python.org › ideas
Dict built-in get/set methods for nested keys - Ideas - Discussions on Python.org
September 21, 2024 - apparently, there is no built-in dict method (let’s call it .nestkey) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures, e.g., dic_1.nestkey(list_of_keys_A) = value instead of manually doing dic_1["key_1"]["subkey_2"]["subsubkey_3"] = value. this is not to be confused with level-1 assignment: dic_1["key_1"] = value_1, dic_2["key_2"] = value_2, ... i know it’s generally good practice to avoid nested structures, but when ...
🌐
Reddit
reddit.com › r/learnpython › how to get value inside nested dictionary
r/learnpython on Reddit: How to get value inside nested dictionary
September 29, 2021 -

I don't know why am I struggling with this, but I am.

I have some data that is a dictionary of dictionaries:

data = {'0': {'account_id': None, 'hero_id': 17, 'player_slot': 0}, '1':             
   {'account_id': 12345678, 'hero_id': 37, 'player_slot': 1}, ...}

What I want to be able to do is grab each account_id . For some reason I can't seem to figure out how to do this.

The closest thing I have been able to do that works, in the sense it runs but isn't actually what I want, is:

for x in data:
    print(x)

# it prints:
> 0
> 1
> ...

If I do the following:

for x in data:
    print(x['account_id']    # TypeError: string indices must be integers
    # or 
    print(x[0])    # IndexError: string index out of range

This is pretty much all I can think to do.

There is clearly something I am not understanding; please can someone tell me what that is and how I should actually be going about this problem?

🌐
Python.org
discuss.python.org › python help
How to find if multi-level key exists in dict? - Python Help - Discussions on Python.org
March 14, 2024 - I’m using Python 3.9 on Windows for the sake of a tutorial. I’m reading an XML file by using xmltodict. It produces a dictionary with nested keys. I would like to see if the key exists before I assign the value of the e…
🌐
Python Forum
python-forum.io › thread-24856.html
Finding value in nested dictionaries with lists
March 7, 2020 - I am struggling with finding a value within a dictionary containing nested dictionaries which in turn can contain nested dictionaries, containing lists etc. The value, to be found, can be anywhere, so within a nested dictionary in a nested dictionary...
🌐
Quora
quora.com › How-do-you-extract-nested-dictionary-data-in-Python
How to extract nested dictionary data in Python - Quora
Answer: let's assume you have a normal dictionary like this. Dictionary is given as key-value pair so the key here is “fruit: and the “value” here is the “apple”. my_dict = { “fruit”:”apple”} to access type my_dict[“fruit”] -> basically passing the key inside the square ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-values-of-particular-key-in-nested-values
Python – Extract values of Particular Key in Nested Values | GeeksforGeeks
January 30, 2025 - Code uses a stack to explore a nested dictionary/list, processing each element without recursion. It collects values of specified key from dictionaries adding nested dictionaries/lists to stack for further exploration.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-safe-access-nested-dictionary-keys
Python | Safe access nested dictionary keys - GeeksforGeeks
May 15, 2023 - Method #1 : Using nested get() This method is used to solve this particular problem, we just take advantage of the functionality of get() to check and assign in absence of value to achieve this particular task.