-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathch_5_practice.txt
47 lines (20 loc) · 1.33 KB
/
ch_5_practice.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
## 1. What does the code for an empty dictionary look like?
{}
## 2. What does a dictionary value with a key 'foo' and a value 42 look like?
tmp = {'foo': 42}
## 3. What is the main difference between a dictionary and a list?
The elements in a list are ordered, and the elements in a dictionary aren't.
Also, elements in a list must be accessed using numerical indices. Elements in a dictionary are indexed using keys, which can have different data types.
## 4. What happens if you try to access spam['foo'] if spam is {'bar': 100}?
You will get a KeyError error.
## 5. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam.keys()?
There is no difference, the expression " 'cat' in spam " checks whether 'cat' is a key in spam.
## 6. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam.values()?
'cat' in spam checks whether'cat' exists as a key in spam. 'cat' in spam.values() checks whether 'cat' is a value in spam.
## 7. What is a shortcut for the following code?
if 'color' not in spam:
spam['color'] = 'black'
spam.setdefault('color','black')
## 8. What module and function can be used to “pretty print” dictionary values?
The module is pprint.
The functions are pprint.pprint() and pprint.pformat().