Learn Before
Dictionary Methods
Dictionaries have several useful built-in methods for altering dictionary values.
- Updating/adding to a dictionary: A dictionary can be updated by passing in an iterable object with key:value pairs (usually another dictionary) into the update method. In the example below, the "apple" key is assigned the new value "green".
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } dict.update({"apple": "green"})
Additionally, if a key/value pair that doesn't exist in the dictionary is passed through the update method, it is added. This is shown below.
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } dict.update({"tangerine": "orange"})
-Removing values from a dictionary: There are multiple ways of removing values from a dictionary. To remove a specific item, you can use the pop or del method by passing in the key name.
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } dict.pop("banana") del dict["apple"]
If you want to remove the last item in the dictionary, you can use the popitem method.
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } dict.popitem() #There are no parameters passed in, since popitem always removes the #last item in the dictionary.
You can also either remove every item from the dictionary using the clear method or delete the structure itself using the del method.
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } dict.clear() #dictionary is emptied, but still exists. It can be updated with new items if you want. del dict #dictionary is actually deleted. Referencing it again will cause an error.
-Looping over a dictionary Like removing items, there are multiple ways of iterating over dictionary items depending on if you want keys, values, or both. You will iterate via a for loop and either use the key method to return only keys, the values method to return only values, or the items method to return the full key:value pair.
dict = { "banana": "yellow", "apple": "red", "grape": "purple" } for x in dict.keys(): print(x) for x in dict.values(): print(x) for x, y in dict.items(): print(x, y)
Other methods that may be used include:
- copy()
- fromkeys()
- get()
- setdefault()
0
1
Contributors are:
Who are from:
Tags
Python Programming Language
Data Science