working on stuff · rvlambda/python-tutorial@811da97 · GitHub
Skip to content

Commit 811da97

Browse files
committed
working on stuff
1 parent 85108ad commit 811da97

6 files changed

Lines changed: 249 additions & 85 deletions

File tree

TODO.md

Lines changed: 8 additions & 18 deletions

dicts.md

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
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+
```

loops.md

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
In programming, a **loop** means repeating something multiple times.
44
There are different kinds of loops:
55

6-
- **While loops** repeat something while a condition is true.
7-
- **Until loops** repeat something until a condition is true.
8-
- **For loops** repeat something for each element of a sequence.
6+
- [While loops](#while-loops) repeat something while a condition is true.
7+
- [Until loops](#until-loops) repeat something while a condition is false.
8+
- [For loops](#for-loops) repeat something for each element of a list.
99

1010
We'll talk about all of these in this tutorial.
1111

@@ -230,11 +230,22 @@ how about you
230230
Note that `for thing in stuff:` is not same as `for (thing in stuff):`.
231231
Here the `in` keyword is just a part of the for loop and it has a
232232
different meaning than it would have if we had `thing in stuff` without
233-
a `for`.
233+
a `for`. Trying to do `for (thing in stuff):` creates an error:
234+
235+
```py
236+
>>> for (thing in stuff):
237+
File "<stdin>", line 1
238+
for (thing in stuff):
239+
^
240+
SyntaxError: invalid syntax
241+
>>>
242+
```
234243

235244
Right now the while loop version might seem easier to understand for
236245
you, but later you'll realize that for loops are much easier to work
237246
with than while loops and index variables, especially in large projects.
247+
For looping is also a little bit faster than while looping with an index
248+
variable.
238249

239250
There's only one big limitation with for looping over lists. We
240251
shouldn't modify the list in the for loop. If we do, the results can

modules.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ that are built into Python. The official documentation is
217217
>>> # stdin is short for standard input
218218
>>> # stdout is short for standard output
219219
>>> # stderr is short for standard errors
220-
>>> print("Hello!", file=sys.stdout)
220+
>>> print("Hello!", file=sys.stdout) # this is where prints go by default
221221
Hello!
222222
>>> print("Hello!", file=sys.stderr) # use this for error messages
223223
Hello!

trey-hunner-zip-and-enumerate.md

Lines changed: 4 additions & 62 deletions

0 commit comments

Comments
 (0)