![]() |
|
[Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? (/thread-97505.html) |
[Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? - xSicKxBot - 09-29-2020 How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? Summary: To update a key in a dictionary if it doesn’t exist, you can check if it is present in the dictionary using the Code: inCode: update()Code: sCode: etdefault(key[, default])Problem: Given a dictionary; how to update a key in it if the key does not exist? Example: Code: device = { "brand": "Apple", "model": "iPhone 11",
} < Some Method to Check if key-value pairs "color" : "red" and "year" : 2019 exists or not and then update/insert it in the dictionary > print(device)Output: Code: {'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}To solve our problem statement, let us follow a modular approach and break down our discussion in this article into three parts.
Without further delay let us dive into the solutions right away. Section 1: Insert/Update A Key In A Dictionary [b]Method 1: Create A New Key-Value Pair Assign It To Dictionary | Subscript Notation[/b] We can create a new index key and then assign a value to it and then assign the key-value pair to the dictionary. Let us have a look at the following program which explains the syntax to create a new key-value pair and assign it to the dictionary: Code: device = { "brand": "Apple", "model": "iPhone 11",
} device["year"] = 2019
print(device)Output: {‘brand’: ‘Apple’, ‘year’: 2019, ‘model’: ‘iPhone 11’} [b]Method 2: Use The update() Function[/b] The Code: update()The following code demonstrates the usage of the Code: update()Code: device = { "brand": "Apple", "model": "iPhone 11",
} device.update({"year" : 2019})
print(device)Output: Code: {'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}We can combine an existing dictionary and a key-value pair using the * operator. Let us have a look at the following code to understand the concept and usage of the * operator to insert items in a dictionary. Code: device = { "brand": "Apple", "model": "iPhone 11",
}
device = {**device,**{"year":2019}}
print(device)Output: Code: {'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}Disclaimer: In the above methods if we do not check the presence of a key in the dictionary, then the value will be overwritten in the dictionary if the key and value are already existing in the dictionary. Now, that brings us to the second section of our discussion! Section 2: Check If A Key Is Present In A Dictionary [b]Method 1: Using The in Keyword[/b] The Code: inCode: inCode: device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if "year" in device: print("key year is present!")
else: print("key year is not Present!") if "color" in device: print("key color is present!")
else: print("key color is not present!")Output: Code: key year is present!
key color is not present! Note: Just like the Code: inCode: not in[b]Method 2: Using keys() Function[/b] Code: keys()Let us have a look a the following program to understand how to use the Code: keys()Code: device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if "year" in device.keys(): print("key year is present!")
else: print("key year is not Present!") if "color" in device.keys(): print("key color is present!")
else: print("key color is not present!")Output: Code: key year is present!
key color is not present!If you are using Python 2.x then you might fancy your chances with the has_key() method which is an inbuilt method in Python that returns true if the specified key is present in the dictionary else it returns false. Caution: Code: has_key()Code: inNow let us have a look at the following program to understand how we can use the Code: has_key()Code: device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if device.has_key("year"): print("key year is present!")
else: print("key year is not Present!") if device.has_key("color"): print("key color is present!")
else: print("key color is not present!")Output: Code: key year is present!
key color is not present!Phew!!! Now, we are finally equipped with all the procedures to check as well as update a key in a dictionary if it does not exist in the dictionary. That brings us to the final stages of our discussion where we shall combine our knowledge from section 1 and section 2 to reach the desired output. Update Key In Dictionary If It Doesn’t Exist [b]Solution 1: Using Concepts Discussed In Section 1 and Section 2[/b] Since we are through with the concepts, let us dive into the program to implement them and get the final output: Code: device = { "brand": "Apple", "model": "iPhone 11",
} # Method 1 : Create a New Key_Value pair and check using the in keyword
if "color" not in device: device["color"] = "red" # Method 2 : Use update() method and check using the not in keyword
if "year" not in device.keys(): device.update({"year" : 2019}) # Method 2 : Use * operator and check using the not in keyword
if "brand" not in device.keys(): device.update({"brand" : "Samsung" })
else: print(device)Output: Code: {'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}Code: setdefault()Let us have a look at the following program which explains the Code: setdefault()Code: device = { "brand": "Apple", "model": "iPhone 11", "color": "red"
} device.setdefault('year',2019)
print(device)Output: Code: {'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}I hope after reading this article you can check and update values in a dictionary with ease. In case you have any doubts regarding Python dictionaries, I highly recommend you to go through our tutorial on Python dictionaries. Please subscribeand stay tuned for more interesting articles! Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! The post How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? first appeared on Finxter. |