-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionary Example2
More file actions
44 lines (24 loc) · 1.2 KB
/
Dictionary Example2
File metadata and controls
44 lines (24 loc) · 1.2 KB
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
43
44
Lists inside of dictionaries
Your gonna see lots of lists inside dictionaries and dictionaries inside lists. This can get kind of crazy but stick with me.
animal_sounds = {
"cat": ["meow", "purr"],
"dog": ["woof", "bark"],
"fox": []
}
We can do this for users as well.
mattan = {'name': 'Mattan', 'height': 70, 'shoe size': 10.5, 'hair': 'Brown', 'eyes': 'Brown'}
chris = {'name': 'Chris', 'height': 68, 'shoe size': 10, 'hair': 'Brown', 'eyes': 'Brown'}
sarah = {'name': 'Sarah', 'height': 72, 'shoe size': 8, 'hair': 'Brown', 'eyes': 'Brown'}
Create a list
But now let's create a list:
people = [mattan, chris, sarah]
print(people)
Remember that these variables inside our list are now all dictionaries. If you print the list, you'll get all the dictionaries.
If you wanted to just print out the height of each person, you can loop over the list people, and realize that they all have the same keys. So you could use person['height'] to get their height.
Loops
The loop looks like this:
for person in people:
print(person['height'])
Note this only works because I know all the dictionaries have the 'height' key. A safer option might be:
for person in people:
print(person.get('height'))