This article will discuss how to add key-value pairs in the dictionary only when Key does not exist.
Add a key-value pair to the dictionary if Key doesn’t exist
Suppose we have a dictionary of string and integers,
# Dictionary of strings and ints word_freq = {"Hello": 56, "at": 23, "test": 43, "this": 43}
Now, if we want to add a new pair {‘why’: 10} to this dictionary, then it should be added without any problem. It is because the key ‘why’ does not exist in the dictionary yet. Whereas when we try to add a new pair {‘at’: 11} to this dictionary, then it should not be added because key ‘at’ already exists in the dictionary.
To have this kind of behavior, before adding a key-value pair to the dictionary, we need to check if the Key already exists in the dictionary or not. If Key does not exist in the dictionary yet, only add the new pair; otherwise, skip. For example,
# Dictionary of strings and ints word_freq = {"Hello": 56, "at": 23, "test": 43, "this": 43} key = 'how' value = 50 if key not in word_freq: word_freq.update({key: value}) else: print('Key already exist') print(word_freq)
Output:
{'Hello': 56, 'at': 23, 'test': 43, 'this': 43, 'how': 50}
We tried to add a key-value pair whose Key does not exist in the dictionary. Therefore, it got added to the dictionary successfully.
Now let’s try to add a pair whose Key already exists in the dictionary,
# Dictionary of strings and ints word_freq = {"Hello": 56, "at": 23, "test": 43, "this": 43} key = 'at' value = 100 # If key does not exist in dictionary then add new pair if key not in word_freq: word_freq.update({key: value}) else: print('Key already exist') print(word_freq)
Output:
Key already exist {'Hello': 56, 'at': 23, 'test': 43, 'this': 43}
As key ‘at’ was already present in the dictionary, it did not add it.
Function to add key-value pair only if Key does not exist in the dictionary
Using above mentioned techinque, we can insert key-value pair only when Key does not exist in the dictionary. But if we want to add several key-value pairs, it is not practical to write if-else checks for every Key. So, let’s create a function for the same, which will make our life litlle easy. For example,
def add_if_key_not_exist(dict_obj, key, value): """ Add new key-value pair to dictionary only if key does not exist in dictionary. """ result = False if key not in dict_obj: word_freq.update({key: value}) result = True if not result: print('Key - ', key, ' - already exists in the dictionary') # Dictionary of strings and ints word_freq = {"Hello": 56, "at": 23, "test": 43, "this": 43} add_if_key_not_exist(word_freq, 'at', 20) add_if_key_not_exist(word_freq, 'how', 23) print(word_freq)
Output:
Key - at - already exists in the dictionary {'Hello': 56, 'at': 23, 'test': 43, 'this': 43, 'how': 23}
Here, we added multiple key-value pairs to the dictionary only if key does not exist in the dictionary.
Summary:
Today we learned how to add key-value pairs to the dictionary only when the given key does not exist.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.