Skip to main content
  1. Posts/

Assignment 7: Add a Key-Value Pair Only if the Key is Not in the Dictionary

·177 words·1 min

So today I will show you how to add a Key-Value Pair Only if the Key is Not in the dictionary.

Plan:

  1. Make a dictionary
  2. print the dict to make sure it works
  3. add a item to the dict
  4. to upgrade the add thing we make a variable called new_key and new_value but still keep the add item thing
  5. if we want to check if the new item exist so we use the if-statement but instead of checking if it exist we check if it doesn’t exist so we use not in and don’t print anything
  6. so since we have the add thing we put it under the for-loop so basically it sees if the new item doesn’t exist and if it doesn’t it will proceed and print the dictionary while if there is a same key name it will skip the program and print the dictionary

Your code should look similar to mine:

dict = {"Jan": 1, "Feb": 2, "Mar": 3}

new_key = "Feb"
new_value = 5

if new_key not in dict:
    dict[new_key] = new_value

print(dict)