Dictionaries are also used very widely in Python. They have the following characteristics.
You can use the dict function to create an empty dictionary or use braces to create a new populated dictionary.
1 2 3 | empty_dict = dict() #creates an empty dictionary populated_dict = {'a': 0, 'b': 1, 'c': 2} |
Note that the keys in a dictionary must be unique. If you provide multiple same keys only the last value will be stored.
1 2 | Output: {0: 'c', 1: 'b'} |
You can use brackets to get, set or delete values.
1 2 3 4 5 | Output: 0 {'a': 0, 'b': 3, 'c': 2} {'a': 0, 'b': 3, 'c': 2, 'd': 3} {'b': 3, 'c': 2, 'd': 3} |
Please note that if you try to get a key that is not in a dictionary using this method, a KeyError exception will be raised and you will have to deal with it gracefully.
1 2 3 4 | Output: 49 None 0 |
Note: The benefit of using the get method instead of using square brackets, i.e., instead of using “dict1[key1]” is that the get method will NOT throw a KeyError exception if “key1” doesn’t exist in the dictionary.
The get method returns a None instead of throwing an exception.
1 2 | Output: [('a', 76), ('b', 24), ('c', 49)] |
1 2 | Output: ['a', 'b', 'c'] |
1 2 | Output: [76, 24, 49] |
1 2 | Output: {'Mark': 81, 'Fred': 36, 'Alice': 92, 'Jane': 85, 'Michael': 54, 'David': 45, 'Kate': 67} |
Note: You would want to use update only when you want to merge several elements from another dictionary.
1 2 | Output: {'a': 76, 'b': 24, 'c': 49} |
Similarly to lists, you can create a dictionary with a comprehension. Recall that comprehension refers to creating the object by formatting it into a single line of code. This not only makes it easier to write but also improves readability/comprehension.
1 2 | Output: {'Mark': 78, 'Alice': 85, 'Jane': 94} |
Here’s an image that shows a summary of the functions that you would most often be using.