|
| 1 | +# Dictionaries |
| 2 | + |
| 3 | +**TODO:** write the lists-and-tuples.md this tutorial links to. |
| 4 | + |
| 5 | +Now we know how [lists and tuples](lists-and-tuples.md) work and how |
| 6 | +to [for loop](loops.md#for-loops) over them. We also did an exercise |
| 7 | +with code like this: |
| 8 | + |
| 9 | +```py |
| 10 | +userlist = [ |
| 11 | + ('me', 'my password'), |
| 12 | + ('you', 'your password'), |
| 13 | +] |
| 14 | +``` |
| 15 | + |
| 16 | +Then to check if a username and password were correct we did |
| 17 | +`(username, password) in userlist`. Adding new users was also easy as |
| 18 | +appending to that list. |
| 19 | + |
| 20 | +What if we need to check if a username is in the users, but we don't |
| 21 | +need to know the password? `username in userlist` is always False |
| 22 | +because the user list consists of (username,password) pairs, so we need |
| 23 | +to for loop over the whole list: |
| 24 | + |
| 25 | +```py |
| 26 | +username_exists = False |
| 27 | +for user in userlist: |
| 28 | + if user[0] == username: |
| 29 | + username_exists = True |
| 30 | + break |
| 31 | +if username_exists: |
| 32 | + # do something |
| 33 | +``` |
| 34 | + |
| 35 | +Getting a user's password also requires a similar loop: |
| 36 | + |
| 37 | +```py |
| 38 | +password = None |
| 39 | +for user in userlist: |
| 40 | + if user[0] == username: |
| 41 | + password = user[1] |
| 42 | + break |
| 43 | +# make sure password isn't still None and do something with it |
| 44 | +``` |
| 45 | + |
| 46 | +This works just fine because our user list only contains two users, but |
| 47 | +it would be slow if the userlist was bigger. |
| 48 | + |
| 49 | +## What are dictionaries? |
| 50 | + |
| 51 | +A better way to store user information might be a dictionary. |
| 52 | + |
| 53 | +```py |
| 54 | +passwords = { |
| 55 | + 'me': 'my password', |
| 56 | + 'you': 'your password', |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +Here `'me'` and `'you'` are **keys** in the dictionary, and |
| 61 | +`'my password'` and `'your password'` are their **values**. Dictionaries |
| 62 | +are often named by their values. This dictionary has passwords as its |
| 63 | +values so I named the variable `passwords`. |
| 64 | + |
| 65 | +There are a few big differences between dictionaries and lists of pairs: |
| 66 | + |
| 67 | +- Dictionaries are not ordered. There's **no guarantees** about which |
| 68 | + order the username:password pairs appear in when we do something |
| 69 | + with the dictionary. |
| 70 | +- Checking if a key is in the dictionary is simple and fast. We don't |
| 71 | + need to for loop through the whole dictionary. |
| 72 | +- Getting the value of a key is also simple and fast. |
| 73 | +- We can't have the same key in the dictionary multiple times, but |
| 74 | + multiple different keys can have the same value. This means that |
| 75 | + **multiple users can't have the same name, but they can have the |
| 76 | + same passwords**. |
| 77 | + |
| 78 | +But wait... this is a lot like variables are! Our variables are not |
| 79 | +ordered, getting a value of a variable is fast and easy and we can't |
| 80 | +have multiple variables with the same name. |
| 81 | + |
| 82 | +Variables are actually stored in a dictionary. We can get that |
| 83 | +dictionary with the globals function. In this dictionary, keys are |
| 84 | +variable names and values are what our variables point to. |
| 85 | + |
| 86 | +```py |
| 87 | +>>> globals() |
| 88 | +{'userlist': [('me', 'my password'), ('you', 'your password')], |
| 89 | + 'passwords': {'me': 'my password', 'you': 'your password'}, |
| 90 | + ...many other things we don't need to care about... |
| 91 | +} |
| 92 | +>>> |
| 93 | +``` |
| 94 | + |
| 95 | +So if you have trouble remembering how dictionaries work just compare |
| 96 | +them to variables. |
| 97 | + |
| 98 | +## What can we do with dictionaries? |
| 99 | + |
| 100 | +Dictionaries have some similarities with lists. For example, both |
| 101 | +lists and dictionaries have a length. |
| 102 | + |
| 103 | +```py |
| 104 | +>>> len(userlist) # contains two elements |
| 105 | +2 |
| 106 | +>>> len(passwords) # contains two key:value pairs |
| 107 | +2 |
| 108 | +>>> |
| 109 | +``` |
| 110 | + |
| 111 | +We can get a value of a key with `the_dict[key]`. Trying to get the |
| 112 | +value of a non-existing key gives us an error. We can also add new |
| 113 | +key:value pairs by doing `the_dict[key] = value`. |
| 114 | + |
| 115 | +```py |
| 116 | +>>> passwords['me'] |
| 117 | +'my password' |
| 118 | +>>> passwords['you'] |
| 119 | +'your password' |
| 120 | +>>> passwords['lol'] |
| 121 | +Traceback (most recent call last): |
| 122 | + File "<stdin>", line 1, in <module> |
| 123 | +KeyError: 'lol' |
| 124 | +>>> passwords["lol"] = "lol's password" |
| 125 | +>>> passwords |
| 126 | +{'lol': "lol's password", 'you': 'your password', 'me': 'my password'} |
| 127 | +>>> |
| 128 | +``` |
| 129 | + |
| 130 | +For looping over a dictionary gets its keys, and checking if something's |
| 131 | +in the dictionary checks if the dictionary has a key like that. This can |
| 132 | +be confusing at first but you'll get used to this. |
| 133 | + |
| 134 | +```py |
| 135 | +>>> 'me' in passwords |
| 136 | +True |
| 137 | +>>> 'my password' in passwords |
| 138 | +False |
| 139 | +>>> for name in passwords: |
| 140 | +... print(name) |
| 141 | +... |
| 142 | +lol |
| 143 | +you |
| 144 | +me |
| 145 | +>>> |
| 146 | +``` |
| 147 | + |
| 148 | +Dictionaries have a values method that we can use if we want to do |
| 149 | +something with the values: |
| 150 | + |
| 151 | +```py |
| 152 | +>>> passwords.values() |
| 153 | +dict_values(["lol's password", 'your password', 'my password']) |
| 154 | +>>> |
| 155 | +``` |
| 156 | + |
| 157 | +The values method returned a `dict_values` object. Things like this |
| 158 | +behave a lot like lists and usually we don't need to convert them to |
| 159 | +lists. |
| 160 | + |
| 161 | +```py |
| 162 | +>>> for password in passwords.values(): |
| 163 | +... print(password) |
| 164 | +... |
| 165 | +lol's password |
| 166 | +your password |
| 167 | +my password |
| 168 | +>>> |
| 169 | +``` |
| 170 | + |
| 171 | +We can do things like `list(passwords.values())` if we need a real list |
| 172 | +for some reason, but doing that can slow down our program if the |
| 173 | +dictionary is big. There's also a keys method, but usually we don't need |
| 174 | +it because the dictionary itself behaves a lot like a list of keys. |
| 175 | + |
| 176 | +If we need both keys and values we can use the items method with the |
| 177 | +`for first, second in thing` trick. |
| 178 | + |
| 179 | +```py |
| 180 | +>>> passwords.items() |
| 181 | +dict_items([('lol', "lol's password"), |
| 182 | + ('you', 'your password'), |
| 183 | + ('me', 'my password')]) |
| 184 | +>>> for name, password in passwords.items(): |
| 185 | +... print(name + ": " + password) |
| 186 | +... |
| 187 | +lol: lol's password |
| 188 | +you: your password |
| 189 | +me: my password |
| 190 | +>>> |
| 191 | +``` |
0 commit comments