Skip to content

Commit 3b44341

Browse files
committed
way better examples
1 parent 87183fb commit 3b44341

File tree

1 file changed

+107
-82
lines changed

1 file changed

+107
-82
lines changed

basics/dicts.md

Lines changed: 107 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -2,78 +2,81 @@
22

33
Now we know how [lists and tuples](lists-and-tuples.md) work and how
44
to [for loop](loops.md#for-loops) over them. If we make some kind of
5-
program that needs to keep track of people's usernames and passwords,
5+
program that needs to keep track of people's names and favorite pets,
66
we can use a list for that:
77

88
```python
9-
userlist = [
10-
('me', 'my password'),
11-
('you', 'your password'),
9+
names_and_pets = [
10+
('horusr', 'cats'),
11+
('caisa64', 'cats and dogs'),
12+
('__Myst__', 'cats'),
1213
]
1314
```
1415

15-
Then to check if a username and password are correct we can do
16-
`(username, password) in userlist`. Or we can add a new user easily by
17-
appending a new `(username, password)` tuple to the userlist.
16+
Then to check if cats are horusr's favorite pets we can do
17+
`('horusr', 'cats') in names_and_pets`. Or we can add new people's
18+
favorite pets easily by appending new `(name, pets)` tuples to the list.
1819

19-
But what if we need to check if a username exists, but we don't know
20-
the password? `username in userlist` is always False because the user
21-
list consists of `(username, password)` pairs instead of just
22-
usernames, so we need to for loop over the whole userlist:
20+
But what if we need to check if we know anything about someone's
21+
favorite pets? `'caisa64' in names_and_pets` is always False because the
22+
pet list consists of `(name, pets)` pairs instead of just names, so we
23+
need to for loop over the whole pet list:
2324

2425
```python
25-
username_exists = False
26-
for user in userlist:
27-
if user[0] == username:
28-
username_exists = True
26+
found_caisa64 = False
27+
for pair in names_and_pets:
28+
if pair[0] == 'caisa64':
29+
found_caisa64 = True
2930
break
30-
if username_exists:
31+
if found_caisa64:
3132
# do something
3233
```
3334

34-
Or how about getting a user's password if we know the username? This
35+
Or what if we need to find out what caisa64's favorite pets are? That
3536
also requires going through the whole list.
3637

3738
```python
38-
password = None
39-
for user in userlist:
40-
if user[0] == username:
41-
password = user[1]
39+
pets = None
40+
for pair in names_and_pets:
41+
if pair[0] == 'caisa64':
42+
pets = pair[1]
4243
break
43-
# make sure password is not None and do something with it
44+
# make sure pets is not None and do something with it
4445
```
4546

46-
As you can see, a list of `(username, password)` pairs is not an ideal
47-
way to store our usernames and passwords.
47+
As you can see, a list of `(name, pets)` pairs is not an ideal
48+
way to store names and favorite pets.
4849

4950
## What are dictionaries?
5051

51-
A better way to store user information might be a dictionary:
52+
A better way to store information about favorite pets might be a
53+
dictionary:
5254

5355
```python
54-
passwords = {
55-
'me': 'my password',
56-
'you': 'your password',
56+
favorite_pets = {
57+
'horusr': 'cats',
58+
'caisa64': 'cats and dogs',
59+
'__Myst__': 'cats',
5760
}
5861
```
5962

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`.
63+
Here `'horusr'` and `'caisa64'` are **keys** in the dictionary, and
64+
`'cats'` and `'cats and docs'` are their **values**. Dictionaries are
65+
often named by their values. This dictionary has favorite pets as its
66+
values so I named the variable `favorite_pets`.
6467

6568
There are a few big differences between dictionaries and lists of pairs:
6669

6770
- Dictionaries are not ordered. There are **no guarantees** about which
68-
order the `username: password` pairs appear in when we do something
71+
order the `name: pets` pairs appear in when we do something
6972
with the dictionary.
7073
- Checking if a key is in the dictionary is simple and fast. We don't
7174
need to for loop through the whole dictionary.
7275
- Getting the value of a key is also simple and fast.
7376
- We can't have the same key in the dictionary multiple times, but
7477
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**.
78+
**multiple people can't have the same name, but they can have the
79+
same favorite pets**.
7780

7881
But wait... this is a lot like variables are! Our variables are not
7982
ordered, getting a value of a variable is fast and easy and we can't
@@ -85,28 +88,32 @@ variable names and values are what our variables point to.
8588

8689
```python
8790
>>> globals()
88-
{'userlist': [('me', 'my password'), ('you', 'your password')],
89-
'passwords': {'me': 'my password', 'you': 'your password'},
91+
{'names_and_pets': [('horusr', 'cats'),
92+
('caisa64', 'cats and dogs'),
93+
('__Myst__', 'cats')],
94+
'favorite_pets': {'__Myst__': 'cats',
95+
'caisa64': 'cats and dogs',
96+
'horusr': 'cats'},
9097
...many other things we don't need to care about...
9198
}
9299
>>>
93100
```
94101

95102
So if you have trouble remembering how dictionaries work just compare
96-
them to variables. A dictionary is a perfect way to store our usernames
97-
and passwords. We don't care about which order the users were added in,
98-
it's impossible to add multiple users with the same username and
99-
getting a user's password is easy.
103+
them to variables. A dictionary is a perfect way to store these names
104+
and favorite pets. We don't care about which order the names and pets
105+
were added in, it's impossible to add the same name multiple times and
106+
getting someone's favorite pets is easy.
100107

101108
## What can we do with dictionaries?
102109

103110
Dictionaries have some similarities with lists. For example, both
104111
lists and dictionaries have a length.
105112

106113
```python
107-
>>> len(userlist) # contains two elements
114+
>>> len(names_and_pets) # contains two elements
108115
2
109-
>>> len(passwords) # contains two key:value pairs
116+
>>> len(favorite_pets) # contains two key:value pairs
110117
2
111118
>>>
112119
```
@@ -115,26 +122,38 @@ We can get a value of a key with `the_dict[key]`. This is a lot easier
115122
and faster than for-looping over a list of pairs.
116123

117124
```python
118-
>>> passwords['me']
119-
'my password'
120-
>>> passwords['you']
121-
'your password'
125+
>>> favorite_pets['caisa64']
126+
'cats and dogs'
127+
>>> favorite_pets['__Myst__']
128+
'cats'
122129
>>>
123130
```
124131

125-
Trying to get the value of a non-existing key gives us an error, but we
126-
can add new `key: value` pairs by doing `the_dict[key] = value`.
132+
Trying to get the value of a non-existing key gives us an error.
127133

128134
```python
129-
>>> passwords['lol']
135+
>>> favorite_pets['Akuli']
130136
Traceback (most recent call last):
131137
File "<stdin>", line 1, in <module>
132-
KeyError: 'lol'
133-
>>> passwords["lol"] = "lol's password"
134-
>>> passwords["lol"]
135-
"lol's password"
136-
>>> passwords
137-
{'lol': "lol's password", 'you': 'your password', 'me': 'my password'}
138+
KeyError: 'Akuli'
139+
>>>
140+
```
141+
142+
But we can add new `key: value` pairs or change the values of existing
143+
keys by doing `the_dict[key] = value`.
144+
145+
```python
146+
>>> favorite_pets['Akuli'] = 'penguins'
147+
>>> favorite_pets['Akuli']
148+
'penguins'
149+
>>> favorite_pets['Akuli'] = 'dogs'
150+
>>> favorite_pets['Akuli']
151+
'dogs'
152+
>>> favorite_pets
153+
{'__Myst__': 'cats',
154+
'Akuli': 'dogs',
155+
'horusr': 'cats',
156+
'caisa64': 'cats and dogs'}
138157
>>>
139158
```
140159

@@ -143,25 +162,26 @@ is in the dictionary checks if the dictionary has a key like that. This
143162
can be confusing at first but you'll get used to this.
144163

145164
```python
146-
>>> 'me' in passwords
165+
>>> 'Akuli' in favorite_pets
147166
True
148-
>>> 'my password' in passwords
167+
>>> 'dogs' in favorite_pets
149168
False
150-
>>> for name in passwords:
169+
>>> for name in favorite_pets:
151170
... print(name)
152171
...
153-
lol
154-
you
155-
me
172+
caisa64
173+
Akuli
174+
__Myst__
175+
horusr
156176
>>>
157177
```
158178

159179
Dictionaries have a values method that we can use if we want to do
160180
something with the values:
161181

162182
```python
163-
>>> passwords.values()
164-
dict_values(["lol's password", 'your password', 'my password'])
183+
>>> favorite_pets.values()
184+
dict_values(['dogs', 'cats', 'cats and dogs', 'cats'])
165185
>>>
166186
```
167187

@@ -170,44 +190,47 @@ behave a lot like lists and usually we don't need to convert them to
170190
lists.
171191

172192
```python
173-
>>> for password in passwords.values():
174-
... print(password)
193+
>>> for pets in favorite_pets.values():
194+
... print(pets)
175195
...
176-
lol's password
177-
your password
178-
my password
196+
dogs
197+
cats
198+
cats and dogs
199+
cats
179200
>>>
180201
```
181202

182-
We can do things like `list(passwords.values())` if we need a real list
183-
for some reason, but doing that can slow down our program if the
203+
We can do things like `list(favorite_pets.values())` if we need a real
204+
list for some reason, but doing that can slow down our program if the
184205
dictionary is big. There's also a keys method, but usually we don't need
185206
it because the dictionary itself behaves a lot like a list of keys.
186207

187208
If we need both keys and values we can use the items method with the
188209
`for first, second in thing` trick.
189210

190211
```python
191-
>>> passwords.items()
192-
dict_items([('lol', "lol's password"),
193-
('you', 'your password'),
194-
('me', 'my password')])
195-
>>> for name, password in passwords.items():
196-
... print(name + ": " + password)
212+
>>> favorite_pets.items()
213+
dict_items([('Akuli', 'dogs'),
214+
('__Myst__', 'cats'),
215+
('caisa64', 'cats and dogs'),
216+
('horusr', 'cats')])
217+
>>> for name, pets in favorite_pets.items():
218+
... print("{} are {}'s favorite pets".format(pets, name))
197219
...
198-
lol: lol's password
199-
you: your password
200-
me: my password
220+
dogs are Akuli's favorite pets
221+
cats are __Myst__'s favorite pets
222+
cats and dogs are caisa64's favorite pets
223+
cats are horusr's favorite pets
201224
>>>
202225
```
203226

204227
This is also useful for checking if the dictionary has a `key: value`
205228
pair.
206229

207230
```python
208-
>>> ('me', 'my password') in passwords.items() # correct username and password
231+
>>> ('horusr', 'cats') in favorite_pets.items()
209232
True
210-
>>> ('me', 'whatever') in passwords.items() # wrong username or password
233+
>>> ('horusr', 'dogs') in favorite_pets.items()
211234
False
212235
>>>
213236
```
@@ -297,6 +320,8 @@ Running the program might look like this:
297320
and appears once in the sentence
298321
test appears 2 times in the sentence
299322

323+
**TODO:** Exercises.
324+
300325
***
301326

302327
If you have trouble with this tutorial please [tell me about

0 commit comments

Comments
 (0)