|
| 1 | +# Python Dictionary |
| 2 | + |
| 3 | +**Video link:** |
| 4 | + |
| 5 | +In this video, we learned about Python dictionary that allows us to work with key/value pairs. |
| 6 | + |
| 7 | +**Programs in the Video** |
| 8 | + |
| 9 | +- [Create Dictionaries](#create-dictionaries) |
| 10 | +- [Access Dictionary Elements](#access-dictionary-elements) |
| 11 | +- [Add and Change Dictionary Elements](#add-and-change-dictionary-elements) |
| 12 | +- [Remove Elements From a Dictionary](#remove-elements-from-a-dictionary) |
| 13 | +- [Iterating Through a Dictionary](#iterating-through-a-dictionary) |
| 14 | +- [**Task**: Guess the Output](#programming-task) |
| 15 | +--- |
| 16 | + |
| 17 | +## Create Dictionaries |
| 18 | +A dictionary is a collection of key/value pairs. It is similar to associative arrays in other programming languages. |
| 19 | + |
| 20 | +To create a dictionary, we put the key/value pairs separated by a colon `:` inside the curly braces `{}`. |
| 21 | + |
| 22 | +```python |
| 23 | +person1 = {"name": "Linus", "age": 21} |
| 24 | +print(person1) |
| 25 | +``` |
| 26 | + |
| 27 | +**Output** |
| 28 | +``` |
| 29 | +{"name": "Linus", "age": 21} |
| 30 | +``` |
| 31 | + |
| 32 | +|Key|Value| |
| 33 | +|---|---| |
| 34 | +|"name"|"Linus"| |
| 35 | +|"age"|21| |
| 36 | + |
| 37 | +>**Notes:** |
| 38 | +>- Keys of a dictionary can be any immutable objects like numbers, strings and tuples. However, they cannot be objects that can be modified like lists. |
| 39 | +>- Keys must be unique for identification. |
| 40 | +
|
| 41 | +--- |
| 42 | + |
| 43 | +## Access Dictionary Elements |
| 44 | + |
| 45 | +Dictionaries are optimized to get values when the key is known. |
| 46 | + |
| 47 | +Similar to numbered indexes like `0`, `1`, `2` to get elements from sequences like lists and tuples, keys are used as indices for dictionaries. |
| 48 | + |
| 49 | +```python |
| 50 | +person1 = {"name": "Linus", "age": 21} |
| 51 | +print(person1["name"]) |
| 52 | +print(person1["age"]) |
| 53 | +``` |
| 54 | + |
| 55 | +**Output** |
| 56 | + |
| 57 | +``` |
| 58 | +Linus |
| 59 | +21 |
| 60 | +``` |
| 61 | + |
| 62 | +If we try to access a key that is not in the dictionary, we will get `KeyError`. |
| 63 | + |
| 64 | +```python |
| 65 | +person1 = {"name": "Linus", "age": 21} |
| 66 | +print(person1["hobbies"]) |
| 67 | +``` |
| 68 | + |
| 69 | +**Output** |
| 70 | +``` |
| 71 | +Traceback (most recent call last): |
| 72 | + File "<string>", line 2, in <module> |
| 73 | +KeyError: 'hobbies' |
| 74 | +``` |
| 75 | + |
| 76 | +Sometimes instead of getting this error, we may just want to know if the key exists or not and decide what to do based on it |
| 77 | + |
| 78 | +In that case we can use the dictionary's `get()` method: |
| 79 | + |
| 80 | +```python |
| 81 | +person1 = {"name": "Linus", "age": 21} |
| 82 | +print(person1.get("namr")) |
| 83 | +print(person1.get("hobbies")) |
| 84 | +``` |
| 85 | + |
| 86 | +**Output** |
| 87 | +``` |
| 88 | +Linus |
| 89 | +None |
| 90 | +``` |
| 91 | + |
| 92 | +Instead of an error, we get `None` which denotes empty or no value. This value can be used with `if` statement to make different decision as per the need. |
| 93 | + |
| 94 | +We can also pass a second default argument to the `get()` method that will be returned instead of `None` if the key is not found. |
| 95 | + |
| 96 | +```python |
| 97 | +person1 = {"name": "Linus", "age": 21} |
| 98 | +print(person1.get("hobbies", ["dancing", "fishing"])) |
| 99 | +``` |
| 100 | + |
| 101 | +**Output** |
| 102 | +``` |
| 103 | +["dancing", "fishing"] |
| 104 | +``` |
| 105 | + |
| 106 | +--- |
| 107 | + |
| 108 | +## Add and Change Dictionary Elements |
| 109 | + |
| 110 | +```python |
| 111 | +person1 = {"name": "Linus", "age": 21} |
| 112 | + |
| 113 | +# changing existing keys |
| 114 | +person1["name"] = "Dennis" |
| 115 | +print(person1) |
| 116 | + |
| 117 | +# adding new keys |
| 118 | +person1["hobbies"] = ["dancing", "fishing"] |
| 119 | +print(person1) |
| 120 | +``` |
| 121 | + |
| 122 | +**Output** |
| 123 | + |
| 124 | +``` |
| 125 | +{'name': 'Dennis', 'age': 21} |
| 126 | +{'name': 'Dennis', 'age': 21, 'hobbies': ['dancing', 'fishing']} |
| 127 | +``` |
| 128 | + |
| 129 | +--- |
| 130 | + |
| 131 | +## Remove Elements From a Dictionary |
| 132 | + |
| 133 | +To remove an item from the dictionary, we can use the dictionary's `pop()` method. The `pop()` method also returns the value of the removed key. |
| 134 | + |
| 135 | +For example, |
| 136 | + |
| 137 | +```python |
| 138 | +person1 = {"name": "Linus", "age": 21} |
| 139 | +print(person1.pop("name")) |
| 140 | + |
| 141 | +print(person1) |
| 142 | +``` |
| 143 | + |
| 144 | +**Output** |
| 145 | + |
| 146 | +``` |
| 147 | +Linus |
| 148 | +{"age": 21} |
| 149 | +``` |
| 150 | + |
| 151 | +--- |
| 152 | + |
| 153 | +## Iterating Through a Dictionary |
| 154 | + |
| 155 | +Similar to sequences, we can easily iterate through items of a dictionary by using a `for` loop. We get one key in every iteration: |
| 156 | + |
| 157 | +```python |
| 158 | +person1 = {"name": "Linus", "age": 21} |
| 159 | + |
| 160 | +for key in person1: |
| 161 | + print(key) |
| 162 | + print(person1[key]) |
| 163 | +``` |
| 164 | + |
| 165 | +**Output** |
| 166 | + |
| 167 | +``` |
| 168 | +name |
| 169 | +Linus |
| 170 | +age |
| 171 | +21 |
| 172 | +``` |
| 173 | + |
| 174 | +>**Note:** Starting from Python 3.7, the order of items in a dictionary is preserved. So when we iterate through a dictionary, we get the keys in the order in which they are inserted in the dictionary. |
| 175 | +
|
| 176 | +--- |
| 177 | + |
| 178 | +## Programming Task |
| 179 | + |
| 180 | +**Can you guess the output of this program?** |
| 181 | + |
| 182 | +```python |
| 183 | +synonyms = {"mountain": "peak", "forest": "jungle"} |
| 184 | +print("1.", synonyms["mountain"]) |
| 185 | + |
| 186 | +synonyms["terrain"] = "land" |
| 187 | +print("2.", synonyms) |
| 188 | + |
| 189 | +synonyms.pop("forest") |
| 190 | +print("3.", synonyms) |
| 191 | +``` |
| 192 | + |
| 193 | +**Output** |
| 194 | +``` |
| 195 | +1. peak |
| 196 | +2. {'mountain': 'peak', 'forest': 'jungle', 'terrain': 'land'} |
| 197 | +3. {'mountain': 'peak', 'terrain': 'land'} |
| 198 | +``` |
0 commit comments