Handling Missing Keys in Python Dictionaries

| | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

# Python code to showcase the dictionary and
# missing value error

 
# initializing the dictionary

d = { `a` : 1 , ` b` : 2 }

  
# trying to display the value of the missing key

print ( "The value associated with` c` is: " )

print (d [ ` c` ])

Error:

 Traceback (most recent call last): File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in print (d [`c`]) KeyError:` c` 

In the above example, no key named "c" in the dictionary did not give a runtime error. To avoid such conditions and to alert the user that a specific key is missing or send a default message to that location, there are several ways to handle missing keys.

Method 1: Using get ()

The get (key, def_val) method is useful when we need to validate a key. If the key is present, the value associated with the key is printed, otherwise the def_value passed in arguments is returned.

Method 2: Using setdefault ()

setdefault (key, def_value) works like get (), but the difference is that every time key is missing, a new key is created with a def_value associated with the key passed to arguments.

To implement the above functions, click Defaultdict " — it is a container that is defined in a module named " collection ". It takes a function (default factory) as an argument . The default is the factory default is set to "int", that is, 0 . If key is missing — defaultdict, returns and default is displayed by default . It takes precedence over get () or setdefault ().

  • The default is set in the declaration . There is no need to call the function over and over again and pass the same values ​​as arguments. Hence time savings .
  • Implementing defaultdict is faster than get () or setdefault ().

# Python code to demonstrate defaultdict

 
# import & quot; collections & quot; for defaultdict

import collections

 
# default declaration
# sets the default value "Key not found" for missing keys

defd = collections. defaultdict ( lambda : `Key Not found` )

 
# initializing values ​​

defd [ `a` ] = 1

 
# initializing values ​​

defd [ `b` ] = 2

 
# print value

print ( "The value associated with` a` is: " , end = "")

print (defd [ `a` ])

 
# print value associated with & # 39; c & # 39;

print ( "The value associated with` c` is: " , end = " ")

print ( defd [ `c` ])

Output:

 The value associated with `a` is: 1 The value associated with` c` is: Key Not found 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Handling Missing Keys in Python Dictionaries, check other ast Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Schneider Richtgofen

California | 2023-03-23

io Python module is always a bit confusing 😭 Handling Missing Keys in Python Dictionaries is not the only problem I encountered. Checked yesterday, it works!

Ken Krasiko

Munchen | 2023-03-23

COM PHP module is always a bit confusing 😭 Handling Missing Keys in Python Dictionaries is not the only problem I encountered. I am just not quite sure it is the best method

Jan Porretti

Shanghai | 2023-03-23

I was preparing for my coding interview, thanks for clarifying this - Handling Missing Keys in Python Dictionaries in Python is not the simplest one. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically