You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None (unless the dict actually contains None as the value for this key):

value = d.get(key, "empty")
Answer from Tim Pietzcker on Stack Overflow
๐ŸŒ
Real Python
realpython.com โ€บ python-defaultdict
Using the Python defaultdict Type for Handling Missing Keys โ€“ Real Python
March 18, 2026 - With Python dictionaries, you have at least four available ways to handle missing keys: ... If key is in the dictionary, return its value. If not, insert key with a value of default and return default....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-dict-get-value-by-key-default
Python Dict Get Value by Key Default - GeeksforGeeks
July 23, 2025 - With dictionary comprehension we can iterate over the existing dictionary and set default values for the missing keys by checking if they exist or not.
๐ŸŒ
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.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to set a default value when a key doesn't exist in a dictionary?
How to set a default value when a key doesn't exist in a dictionary? : r/learnpython
July 27, 2024 - from collections import defaultdict my_dict =defaultdict(lambda : default, my_dict) value = my_dict[key] Which will automatically create the key with a default if you try to call a key that does not exist.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ default-dictionary-values
Setting default dictionary values in Python - Python Morsels
July 17, 2026 - There's not just one solution to this problem. Let's look at each approach Python provides and discuss when each one is useful. The get method is the classic way to look up a value for a dictionary key without raising an exception for missing keys. ... The get method accepts two arguments: the key to look up and the default value to use if that key isn't in the dictionary.
๐ŸŒ
SysTutorials
systutorials.com โ€บ how-to-get-the-value-of-a-default-value-if-the-key-does-not-exist-in-dict-in-python
How To Get A Dictionary Value With A Default Fallback In Python - SysTutorials
April 13, 2026 - from collections import defaultdict # All missing keys return empty list counters = defaultdict(list) counters['first'].append('item1') print(counters['second']) # [] # Missing keys return 0 word_count = defaultdict(int) word_count['python'] += 1 print(word_count['rust']) # 0 ยท The callable you pass (like list, int, str) is called with no arguments when a key is missing. This is useful for aggregation and counting tasks. For situations where you need to check if a key exists and use its value conditionally: if (user_input := my_dict.get('input')) is not None: process(user_input)
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ defaultdict-in-python
Defaultdict in Python - GeeksforGeeks
Defaultdict is a subclass of the built-in dict class from the collections module. It automatically assigns a default value to keys that do not exist which means no need to manually check for missing keys and avoid KeyError.
Published: May 19, 2026
๐ŸŒ
Fatos Morina
fatosmorina.com โ€บ home โ€บ how to set default values for missing keys in python dictionaries
How to Set Default Values for Missing Keys in Python Dictionaries - Fatos Morina
September 3, 2023 - In the example above, the dictionary my_dict contains keys 'a' and 'b', but not 'c'. By using my_dict.get('c', 0), we are able to set a default value of 0 for the missing key 'c'. The result is that the variable default_value will be assigned 0, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ handling-missing-keys-python-dictionaries
Handling missing keys in Python dictionaries - GeeksforGeeks
August 17, 2026 - If the key doesnโ€™t exist, it adds the key with the given default value. You can handle missing keys by catching the KeyError exception ... dic = {'India': '0091', 'Australia': '0025', 'Nepal': '00977'} try: print(dic['India']) print(dic['USA']) ...
๐ŸŒ
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
Note that the default value defaults to None if a second argument is not provided. The code below initializes a variable called data to an empty string. Then it checks if a certain key called message exists in a dict called dictionary.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-set-a-default-value-for-a-missing-key-in-a-python-dictionary-398066
How to set a default value for a missing key in a Python dictionary | LabEx
There are several ways to set default values in Python dictionaries: As mentioned in the previous section, the get() method allows you to specify a default value to be returned if the key is not found in the dictionary:
๐ŸŒ
Wangonya
wangonya.com โ€บ blog โ€บ handling-missing-dict-keys
Handling missing dict keys | Kelvin Wangonya
February 10, 2022 - Trying to access a non-existent key using this notation: dict[key] raises a KeyError. An easy workaround for this is to use get(key) instead, which returns None if key isnโ€™t found, or get(key, default) which returns default if key isnโ€™t found.
๐ŸŒ
Python Geeks
pythongeeks.org โ€บ python geeks โ€บ learn python โ€บ handling missing keys with the python defaultdict type
Handling Missing Keys With the Python defaultdict Type - Python Geeks
July 3, 2023 - Another method to handle missing keys in Python dictionaries is to use the setdefault() method. This method returns the value of the key if it exists, else it creates a new key with the default value provided as an argument.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Add an Item If the Key Does Not Exist in dict in Python: setdefault | note.nkmk.me
May 6, 2023 - If the key specified in the first argument does not exist, a new item is added. d = {'k1': 1, 'k2': 2} d.setdefault('k3', 3) print(d) # {'k1': 1, 'k2': 2, 'k3': 3} ... The default value of the second argument is None.
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ solved-how-to-return-a-default-value-if-a-dictionary-key-is-not-available-in-python
Solved: How to Return a Default Value If a Dictionary Key Is Not Available in Python
December 5, 2024 - A: You can chain get() calls, ensuring each level provides a default dictionary for safe traversing. A: Generally, using get() is slightly more efficient as it avoids the overhead of exception handling unless a missing key is a common occurrence. We hope you found this post helpful in handling missing keys in Python dictionaries!
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ best way to set default value for dictionary
r/learnpython on Reddit: Best way to set default value for dictionary
February 16, 2024 -

Hi all,

The code snippet I need help with uses the Spotify API to find artists that use certain genres as tags. The variable "results" is a dictionary of dictionaries of three artists who use said genre (I don't know why it's not returned as a json, but I'm not mad). In this dictionary there is a lot of information I don't need, so the function picks out the information I need and makes new, smaller dictionaries that it then appends to a list to be used later on in the program. So far, so good. However, I don't want the program to crash if certain information doesn't exist for an artist down the line. Say if they don't have an image, or whatever.

So, I was wondering if there was a way to have it default to a certain value if a key doesn't exist in the results dictionary. If a key does exist and the value is None, that's fine. The suggested thing is to use defaultdict, which honestly makes my brain fall flat. Would it be 'pythonic' to first make a dictionary on every iteration of the loop with all the values set to None, and then override them if they do exist? I feel like I could make that work, but it feels inelegant.

Here is the function in question:

def find_artists(targets: list = None) -> list:

"""
:param targets: Takes a list of genres to be searched for
:return: Returns a list of dictionaries that contain
the genre, artist_name, follower_count, artist_image, and the url
"""
artists = []

for genre in targets:
    results = spotify.search(q=f'genre:{genre}', type='artist', limit=3)

    for entry in results["artists"]["items"]:
        temp_dict = {
            'genre': genre,
            'artist_name': entry['name'],
            'follower_count': entry['followers']['total'],
            'artist_image': entry['images'][0]['url'],
            'url': entry['external_urls']['spotify']
        }

        artists.append(temp_dict)

return artists

I took a long break from coding, and am just now getting back into it, so I'm rusty as heck. Excuse any obvious errors, but please point them out! Also, let me know if you don't think this would be an issue, I'm not very versed in APIs.

Thanks in advance for your time.

EDIT: Typos and fixed the code block