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:
- Make a dictionary
- print the dict to make sure it works
- add a item to the dict
- to upgrade the add thing we make a variable called
new_keyandnew_valuebut still keep the add item thing - if we want to check if the new item exist so we use the
if-statementbut instead of checking if it exist we check if it doesn’t exist so we usenot inand don’t print anything - so since we have the add thing we put it under the
for-loopso 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)