3) d. Dictionary

Dictionaries are also used very widely in Python. They have the following characteristics.

  • Dictionaries are sets of unique key-value pairs.
  • They are mutable (can be changed).
  • Since Python 3.7 key insertion order is preserved.

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.




Methods:

get(key[, default]): Return a value that is assigned to the key. If key is not in dictionary, return default which if omitted is None

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.




items(): Return a copy of a list of dictionary’s key-value pairs.

1
2
Output:
[('a', 76), ('b', 24), ('c', 49)]




keys(): Return a copy of a list of dictionary’s keys.

1
2
Output:
['a', 'b', 'c']




values(): Return a copy of a list of dictionary’s values.

1
2
Output:
[76, 24, 49]




update(mapping): Add key-value pairs to the dictionary. mapping: can be a dictionary or an iterable of key-value pairs. If keyword arguments are provided they will also be added as key-value pairs.

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.




copy(): Returns a shallow copy of the 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.