Day-5 Dictionaries in Python
Day-5 Dictionaries in Python
Dictionaries do not store their information in any particular order, so you may not get your information back in the
same order you entered it.
Dictionaries allow us to store connected bits of information. For example, you might store a person's name and
age together.
General Syntax
A general dictionary in Python looks something like this:
Contents
What are dictionaries? In [ ]: dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
General Syntax
Example
Since the keys and values in dictionaries can be long, we often write just one key-value pair on a line. You might
Exercises
see dictionaries that look more like this:
Common operations with dictionaries
Adding new key-value pairs
Modifying values in a dictionary In [ ]: dictionary_name = {key_1: value_1,
key_2: value_2,
Removing key-value pairs
key_3: value_3,
Modifying keys in a dictionary }
Exercises
Looping through a dictionary
Looping through all key-value pairs This is a bit easier to read, especially if the values are long.
Looping through all keys in a dictionary
Looping through all values in a dictionary
Looping through a dictionary in order
Exercises Example
Nesting
A simple example involves modeling an actual dictionary.
Lists in a dictionary
Dictionaries in a dictionary
An important note about nesting In [2]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.',
Exercises
'dictionary': 'A collection of key-value pairs.',
Overall Challenges 'function': 'A named set of instructions that defines a set of
actions in Python.',
}
top
We can get individual items out of the dictionary, by giving the dictionary's name, and the key in square brackets:
In [7]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.', The output is identical, but we did it in 3 lines instead of 6. If we had 100 terms in our dictionary, we would still be
'dictionary': 'A collection of key-value pairs.', able to print them out with just 3 lines.
'function': 'A named set of instructions that defines a set of
actions in Python.', The only tricky part about using for loops with dictionaries is figuring out what to call those first two variables. The
} general syntax for this for loop is:
Word: list
Exercises
Meaning: A collection of values that are not connected, but have an order.
Pet Names
Word: dictionary
Meaning: A collection of key-value pairs. Create a dictionary to hold information about pets. Each key is an animal's name, and each value is the kind
of animal.
Word: function For example, 'ziggy': 'canary'
Meaning: A named set of instructions that defines a set of actions in Python. Put at least 3 key-value pairs in your dictionary.
Use a for loop to print out a series of statements such as "Willie is a dog."
This code looks pretty repetitive, and it is. Dictionaries have their own for-loop syntax, but since there are two
kinds of information in dictionaries, the structure is a bit more complicated than it is for lists. Here is how to use a Polling Friends
for loop with a dictionary: Think of a question you could ask your friends. Create a dictionary where each key is a person's name, and
each value is that person's response to your question.
In [7]: python_words = {'list': 'A collection of values that are not connected, but ha Store at least three responses in your dictionary.
ve an order.', Use a for loop to print out a series of statements listing each person's name, and their response.
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of
actions in Python.', In [ ]: # Ex 7.1 : Pet Names
}
# put your code here
# Print out the items in the dictionary.
for word, meaning in python_words.items():
print("\nWord: %s" % word) In [ ]: # Ex 7.2 : Polling Friends
print("Meaning: %s" % meaning)
# put your code here
Word: function
Meaning: A named set of instructions that defines a set of actions in Python.
top
Word: list
Meaning: A collection of values that are not connected, but have an order.
Word: dictionary
Meaning: A collection of key-value pairs. Common operations with dictionaries
There are a few common things you will want to do with dictionaries. These include adding new key-value pairs,
modifying information in the dictionary, and removing items from dictionaries.
Word: list
Meaning: A collection of values that are not connected, but have an order. top
Word: dictionary
Meaning: A collection of key-value pairs.
Modifying values in a dictionary
At some point you may want to modify one of the values in your dictionary. Modifying a value in a dictionary is
pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square
brackets, and set that equal to the new value.
In [17]: python_words = {'list': 'A collection of values that are not connected, but ha In [1]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.', ve an order.',
'dictionary': 'A collection of key-value pairs.', 'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of 'function': 'A named set of instructions that defines a set of
actions in Python.', actions in Python.',
} }
print('dictionary: ' + python_words['dictionary']) # Remove the word 'list' and its meaning.
_ = python_words.pop('list')
# Clarify one of the meanings.
python_words['dictionary'] = 'A collection of key-value pairs. \ # Show the current set of words and meanings.
Each key can be used to access its corresponding print("\n\nThese are the Python words I know:")
value.' for word, meaning in python_words.items():
print("\nWord: %s" % word)
print('\ndictionary: ' + python_words['dictionary']) print("Meaning: %s" % meaning)
Removing key-value pairs If you were going to work with this code, you would certainly want to put the code for displaying the dictionary
into a function. Let's see what this looks like:
You may want to remove some key-value pairs from one of your dictionaries at some point. You can do this using
the same del command you learned to use with lists. To remove a key-value pair, you give the del
command, followed by the name of the dictionary, with the key that you want to delete. This removes the key and
the value as a pair.
python_words = {'list': 'A collection of values that are not connected, but ha
python_words = {'list': 'A collection of values that are not connected, but ha ve an order.',
ve an order.', 'dictionary': 'A collection of key-value pairs.',
'dictionary': 'A collection of key-value pairs.', 'function': 'A named set of instructions that defines a set of
'function': 'A named set of instructions that defines a set of actions in Python.',
actions in Python.', }
}
show_words_meanings(python_words)
show_words_meanings(python_words)
# Remove the word 'list' and its meaning.
# Remove the word 'list' and its meaning. del python_words['list']
del python_words['list']
show_words_meanings(python_words)
show_words_meanings(python_words)
Word: dictionary
Meaning: A collection of key-value pairs. These are the Python words I know:
Word: dictionary
This is much more realistic code.
Meaning: A collection of key-value pairs.
As long as we have a nice clean function to work with, let's clean up our output a little:
Modifying keys in a dictionary
Modifying a value in a dictionary was straightforward, because nothing else depends on the value. Modifying a
key is a little harder, because each key is used to unlock a value. We can change a key in two steps:
Make a new key, and copy the value to the new key.
Delete the old key, which also deletes the old value.
Word: function
Meaning: A named set of instructions that defines a set of actions in Python. The only advantage of using the .keys() in the code is a little bit of clarity. But anyone who knows Python
reasonably well is going to recognize what the second version does. In the rest of our code, we will leave out the
Word: list .keys() when we want this behavior.
Meaning: A collection of values that are not connected, but have an order.
You can pull out the value of any key that you are interested in within your loop, using the standard notation for
Word: dictionary accessing a dictionary value from a key:
Meaning: A collection of key-value pairs.
Key: key_1
Key: key_3
Key: key_2
The value for key_2 is value_2.
In [4]: python_words = {'list': 'A collection of values that are not connected, but ha
Let's show how we might use this in our Python words program. This kind of loop provides a straightforward way ve an order.',
to show only the words in the dictionary: 'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of
actions in Python.',
In [20]: python_words = {'list': 'A collection of values that are not connected, but ha
}
ve an order.',
'dictionary': 'A collection of key-value pairs.',
# Show the words that are currently in the dictionary.
'function': 'A named set of instructions that defines a set of
print("The following Python words have been defined:")
actions in Python.',
for word in python_words:
}
print("- %s" % word)
# Show the words that are currently in the dictionary.
requested_word = ''
print("The following Python words have been defined:") while requested_word != 'quit':
for word in python_words: # Allow the user to choose a word, and then display the meaning for that w
print("- %s" % word) ord.
The following Python words have been defined: requested_word = raw_input("\nWhat word would you like to learn about? (or
- function 'quit') ")
- list if requested_word in python_words.keys():
- dictionary print("\n %s: %s" % (requested_word, python_words[requested_word]))
else:
# Handle misspellings, and words not yet stored.
print("\n Sorry, I don't know that word.")
We can extend this slightly to make a program that lets you look up words. We first let the user choose a word.
When the user has chosen a word, we get the meaning for that word, and display it:
The following Python words have been defined:
- function
In [2]: python_words = {'list': 'A collection of values that are not connected, but ha - list
ve an order.', - dictionary
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of What word would you like to learn about? (or 'quit') list
actions in Python.',
} list: A collection of values that are not connected, but have an order.
# Show the words that are currently in the dictionary. What word would you like to learn about? (or 'quit') dictionary
print("The following Python words have been defined:")
for word in python_words: dictionary: A collection of key-value pairs.
print("- %s" % word)
What word would you like to learn about? (or 'quit') quit
# Allow the user to choose a word, and then display the meaning for that word.
requested_word = raw_input("\nWhat word would you like to learn about? ") Sorry, I don't know that word.
print("\n%s: %s" % (requested_word, python_words[requested_word]))
list: A collection of values that are not connected, but have an order.
This allows the user to select one word that has been defined. If we enclose the input part of the program in a
while loop, the user can see as many definitions as they'd like:
In [6]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.', top
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of
actions in Python.',
} Looping through all values in a dictionary
# Show the words that are currently in the dictionary. Python provides a straightforward syntax for looping through all the values in a dictionary, as well:
print("The following Python words have been defined:")
for word in python_words:
print("- %s" % word) In [15]: my_dict = {'key_1': 'value_1',
'key_2': 'value_2',
requested_word = '' 'key_3': 'value_3',
while requested_word != 'quit': }
# Allow the user to choose a word, and then display the meaning for that w
ord. for value in my_dict.values():
requested_word = raw_input("\nWhat word would you like to learn about? (or print('Value: %s' % value)
'quit') ")
Value: value_1
if requested_word in python_words.keys():
Value: value_3
# This is a word we know, so show the meaning.
Value: value_2
print("\n %s: %s" % (requested_word, python_words[requested_word]))
elif requested_word != 'quit':
# This is not in python_words, and it's not 'quit'.
print("\n Sorry, I don't know that word.") We can use this loop syntax to have a little fun with the dictionary example, by making a little quiz program. The
else: program will display a meaning, and ask the user to guess the word that matches that meaning. Let's start out by
# The word is quit. showing all the meanings in the dictionary:
print "\n Bye!"
The following Python words have been defined: In [16]: python_words = {'list': 'A collection of values that are not connected, but ha
- function ve an order.',
- list 'dictionary': 'A collection of key-value pairs.',
- dictionary 'function': 'A named set of instructions that defines a set of
actions in Python.',
What word would you like to learn about? (or 'quit') function }
function: A named set of instructions that defines a set of actions in Pyth for meaning in python_words.values():
on. print("Meaning: %s" % meaning)
What word would you like to learn about? (or 'quit') list
Now we can add a prompt after each meaning, asking the user to guess the word:
list: A collection of values that are not connected, but have an order.
What word would you like to learn about? (or 'quit') class
What word would you like to learn about? (or 'quit') quit
Bye!
In [2]: python_words = {'list': 'A collection of values that are not connected, but ha In [20]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.', ve an order.',
'dictionary': 'A collection of key-value pairs.', 'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of 'function': 'A named set of instructions that defines a set of
actions in Python.', actions in Python.',
} }
# Print each meaning, one at a time, and ask the user # Print each meaning, one at a time, and ask the user
# what word they think it is. # what word they think it is.
for meaning in python_words.values(): for meaning in python_words.values():
print("\nMeaning: %s" % meaning) print("\nMeaning: %s" % meaning)
guessed_word = raw_input("What word do you think this is? ") # Assume the guess is not correct; keep guessing until correct.
correct = False
# The guess is correct if the guessed word's meaning matches the current m while not correct:
eaning. guessed_word = input("\nWhat word do you think this is? ")
if python_words[guessed_word] == meaning:
print("You got it!") # The guess is correct if the guessed word's meaning matches the curre
else: nt meaning.
print("Sorry, that's just not the right word.") if python_words[guessed_word] == meaning:
print("You got it!")
Meaning: A named set of instructions that defines a set of actions in Python. correct = True
What word do you think this is? function else:
You got it! print("Sorry, that's just not the right word.")
Meaning: A collection of values that are not connected, but have an order. Meaning: A named set of instructions that defines a set of actions in Python.
What word do you think this is? function
Sorry, that's just not the right word. What word do you think this is? function
You got it!
Meaning: A collection of key-value pairs.
What word do you think this is? dictionary Meaning: A collection of values that are not connected, but have an order.
You got it!
What word do you think this is? dictionary
Sorry, that's just not the right word.
This is starting to work, but we can see from the output that the user does not get the chance to take a second
What word do you think this is? list
guess if they guess wrong for any meaning. We can use a while loop around the guessing code, to let the user
You got it!
guess until they get it right:
Meaning: A collection of key-value pairs.
This is better. Now, if the guess is incorrect, the user is caught in a loop that they can only exit by guessing
correctly. The final revision to this code is to show the user a list of words to choose from when they are asked to
guess:
In [8]: python_words = {'list': 'A collection of values that are not connected, but ha A named set of instructions that defines a set of actions in Python.
ve an order.',
'dictionary': 'A collection of key-value pairs.', What word do you think this is?
'function': 'A named set of instructions that defines a set of function list dictionary
actions in Python.', - function
} You got it!
def show_words(python_words): A collection of values that are not connected, but have an order.
# A simple function to show the words in the dictionary.
display_message = "" What word do you think this is?
for word in python_words.keys(): function list dictionary
display_message += word + ' ' - dictionary
print display_message Sorry, that's just not the right word.
# Print each meaning, one at a time, and ask the user What word do you think this is?
# what word they think it is. function list dictionary
for meaning in python_words.values(): - list
print("\n%s" % meaning) You got it!
# Assume the guess is not correct; keep guessing until correct. A collection of key-value pairs.
correct = False
while not correct: What word do you think this is?
function list dictionary
print("\nWhat word do you think this is?") - dictionary
show_words(python_words) You got it!
guessed_word = raw_input("- ")
# The guess is correct if the guessed word's meaning matches the curre top
nt meaning.
if python_words[guessed_word] == meaning:
print("You got it!")
correct = True
else: Looping through a dictionary in order
print("Sorry, that's just not the right word.")
Dictionaries are quite useful because they allow bits of information to be connected. One of the problems with
dictionaries, however, is that they are not stored in any particular order. When you retrieve all of the keys or
values in your dictionary, you can't be sure what order you will get them back. There is a quick and easy way to
do this, however, when you want them in a particular order.
Let's take a look at the order that results from a simple call to dictionary.keys():
In [2]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of
actions in Python.',
}
function
list
dictionary
The resulting list is not in order. The list of keys can be put in order by passing the list into the sorted() function,
in the line that initiates the for loop: Exercises
Mountain Heights
In [3]: python_words = {'list': 'A collection of values that are not connected, but ha
ve an order.',
Wikipedia has a list of the tallest mountains in the world
'dictionary': 'A collection of key-value pairs.',
(http://en.wikipedia.org/wiki/List_of_mountains_by_elevation), with each mountain's elevation. Pick five
'function': 'A named set of instructions that defines a set of
actions in Python.', mountains from this list.
} Create a dictionary with the mountain names as keys, and the elevations as values.
Print out just the mountains' names, by looping through the keys of your dictionary.
for word in sorted(python_words.keys()): Print out just the mountains' elevations, by looping through the values of your dictionary.
print(word)
Print out a series of statements telling how tall each mountain is: "Everest is 8848 meters tall."
dictionary Revise your output, if necessary.
function Make sure there is an introductory sentence describing the output for each loop you write.
list Make sure there is a blank line between each group of statements.
Mountain Heights 2
This approach can be used to work with the keys and values in order. For example, the words and meanings can
be printed in alphabetical order by word: Revise your final output from Mountain Heights, so that the information is listed in alphabetical order by each
mountain's name.
In [8]: python_words = {'list': 'A collection of values that are not connected, but ha That is, print out a series of statements telling how tall each mountain is: "Everest is 8848 meters tall."
ve an order.', Make sure your output is in alphabetical order.
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of
actions in Python.',
In [ ]: # Ex 7.5 : Mountain Heights
}
# put your code here
for word in sorted(python_words.keys()):
print("%s: %s" % (word.title(), python_words[word]))
In [ ]: # Ex 7.6 : Mountain Heights 2
Dictionary: A collection of key-value pairs.
Function: A named set of instructions that defines a set of actions in Pytho # put your code here
n.
List: A collection of values that are not connected, but have an order.
top
In this example, the keys have been put into alphabetical order in the for loop only; Python has not changed the
way the dictionary is stored at all. So the next time the dictionary is accessed, the keys could be returned in any
order. There is no way to permanently specify an order for the items in an ordinary dictionary, but if you want to
do this you can use the OrderedDict (http://docs.python.org/3.3/library/collections.html#ordereddict-objects)
Nesting
structure. Nesting is one of the most powerful concepts we have come to so far. Nesting involves putting a list or dictionary
inside another list or dictionary. We will look at two examples here, lists inside of a dictionary and dictionaries
inside of a dictionary. With nesting, the kind of information we can model in our programs is expanded greatly.
top
In [7]: # This program stores people's favorite numbers, and displays them.
favorite_numbers = {'eric': [3, 11, 19, 23, 42],
Lists in a dictionary 'ever': [2, 4, 5],
'willie': [5, 35, 120],
A dictionary connects two pieces of information. Those two pieces of information can be any kind of data }
structure in Python. Let's keep using strings for our keys, but let's try giving a list as a value.
# Display each person's favorite numbers.
The first example will involve storing a number of people's favorite numbers. The keys consist of people's for name in favorite_numbers:
names, and the values are lists of each person's favorite numbers. In this first example, we will access each print("\n%s's favorite numbers are:" % name.title())
person's list one at a time. print(favorite_numbers[name])
We are really just working our way through each key in the dictionary, so let's use a for loop to go through the
keys in the dictionary:
sparse_matrix = {}
sparse_matrix[0] = {1: 12.3, 23: 25.5}
sparse_matrix[1] = {3: 12.0, 15: 25.5}
sparse_matrix[1][15]
full_matrix[1][2]
Out[21]: 3
In [13]: # This program stores people's favorite numbers, and displays them. In [15]: # This program stores people's favorite numbers, and displays them.
favorite_numbers = {'eric': [3, 11, 19, 23, 42], favorite_numbers = {'eric': [3, 11, 19, 23, 42],
'ever': [2, 4, 5], 'ever': [2, 4, 5],
'willie': [5, 35, 120], 'willie': [5, 35, 120],
} }
# Display each person's favorite numbers. # Display each person's favorite numbers.
for name in favorite_numbers: for name in favorite_numbers:
print("\n%s's favorite numbers are:" % name.title()) print("\n%s's favorite numbers are:" % name.title())
# Each value is itself a list, so we need another for loop
# to work with the list. # Each value is itself a list, so let's put that list in a variable.
for favorite_number in favorite_numbers[name]: current_favorite_numbers = favorite_numbers[name]
print(favorite_number) for favorite_number in current_favorite_numbers:
print(favorite_number)
Willie's favorite numbers are:
5 Willie's favorite numbers are:
35 5
120 35
120
Ever's favorite numbers are:
2 Ever's favorite numbers are:
4 2
5 4
5
Eric's favorite numbers are:
3 Eric's favorite numbers are:
11 3
19 11
23 19
42 23
42
Things get a little more complicated inside the for loop. The value is a list of favorite numbers, so the for loop
pulls each favorite_number out of the list one at a time. If it makes more sense to you, you are free to store the top
list in a new variable, and use that to define your for loop:
Dictionaries in a dictionary
The most powerful nesting concept we will cover right now is nesting a dictionary inside of a dictionary.
To demonstrate this, let's make a dictionary of pets, with some information about each pet. The keys for this
dictionary will consist of the pet's name. The values will include information such as the kind of animal, the
owner, and whether the pet has been vaccinated.
In [24]: # This program stores information about pets. For each pet, In [12]: # This program stores information about pets. For each pet,
# we store the kind of animal, the owner's name, and # we store the kind of animal, the owner's name, and
# the breed. # the breed.
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True}, pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False}, 'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}, 'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},
} }
# Let's show all the information for each pet. # Let's show all the information for each pet.
print("Here is what I know about Willie:") for pet_name, pet_information in pets.items():
print("kind: " + pets['willie']['kind']) print("\nHere is what I know about %s:" % pet_name.title())
print("owner: " + pets['willie']['owner']) print("kind: " + pet_information['kind'])
print("vaccinated: " + str(pets['willie']['vaccinated'])) print("owner: " + pet_information['owner'])
print("vaccinated: " + str(pet_information['vaccinated']))
print("\nHere is what I know about Walter:")
print("kind: " + pets['walter']['kind'])
Here is what I know about Peso:
print("owner: " + pets['walter']['owner'])
kind: dog
print("vaccinated: " + str(pets['walter']['vaccinated']))
owner: chloe
vaccinated: True
print("\nHere is what I know about Peso:")
print("kind: " + pets['peso']['kind'])
Here is what I know about Willie:
print("owner: " + pets['peso']['owner'])
kind: dog
print("vaccinated: " + str(pets['peso']['vaccinated']))
owner: eric
vaccinated: True
Here is what I know about Willie:
kind: dog Here is what I know about Walter:
owner: eric kind: cockroach
vaccinated: True owner: eric
vaccinated: False
Here is what I know about Walter:
kind: cockroach
owner: eric
vaccinated: False This code is much shorter and easier to maintain. But even this code will not keep up with our dictionary. If we
add more information to the dictionary later, we will have to update our print statements. Let's put a second for
Here is what I know about Peso: loop inside the first loop in order to run through all the information about each pet:
kind: dog
owner: chloe
vaccinated: True
Clearly this is some repetitive code, but it shows exactly how we access information in a nested dictionary. In the
first set of print statements, we use the name 'willie' to unlock the 'kind' of animal he is, the 'owner' he has,
and whether or not he is 'vaccinated'. We have to wrap the vaccination value in the str function so that Python
knows we want the words 'True' and 'False', not the values True and False . We then do the same thing for
each animal.
Let's rewrite this program, using a for loop to go through the dictionary's keys:
In [13]: # This program stores information about pets. For each pet, In [3]: # This program stores information about pets. For each pet,
# we store the kind of animal, the owner's name, and # we store the kind of animal, the owner's name, and
# the breed. # the breed.
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True}, pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False}, 'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}, 'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},
} }
# Let's show all the information for each pet. # Let's show all the information for each pet.
for pet_name, pet_information in pets.items(): for pet_name, pet_information in pets.items():
print("\nHere is what I know about %s:" % pet_name.title()) print("\nHere is what I know about %s:" % pet_name.title())
# Each animal's dictionary is in 'information' # Each animal's dictionary is in pet_information
for key in pet_information: for key in pet_information:
print(key + ": " + str(pet_information[key])) if key == 'owner':
# Capitalize the owner's name.
Here is what I know about Peso: print(key + ": " + pet_information[key].title())
owner: chloe elif key == 'vaccinated':
kind: dog # Print 'yes' for True, and 'no' for False.
vaccinated: True vaccinated = pet_information['vaccinated']
if vaccinated:
Here is what I know about Willie: print('vaccinated: yes')
owner: eric else:
kind: dog print('vaccinated: no')
vaccinated: True else:
# No special formatting needed for this key.
Here is what I know about Walter: print(key + ": " + pet_information[key])
owner: eric
kind: cockroach Here is what I know about Peso:
vaccinated: False kind: dog
vaccinated: yes
owner: Chloe
This nested loop can look pretty complicated, so again, don't worry if it doesn't make sense for a while.
Here is what I know about Walter:
The first loop gives us all the keys in the main dictionary, which consist of the name of each pet. kind: cockroach
vaccinated: no
Each of these names can be used to 'unlock' the dictionary of each pet.
owner: Eric
The inner loop goes through the dictionary for that individual pet, and pulls out all of the keys in that
individual pet's dictionary. Here is what I know about Willie:
We print the key, which tells us the kind of information we are about to see, and the value for that key. kind: dog
You can see that we could improve the formatting in the output. vaccinated: yes
owner: Eric
We could capitalize the owner's name.
We could print 'yes' or 'no', instead of True and False.
This code is a lot longer, and now we have nested if statements as well as nested for loops. But keep in mind,
this structure would work if there were 1000 pets in our dictionary, and it would work if we were storing 1000
Let's show one last version that uses some if statements to clean up our data for printing: pieces of information about each pet. One level of nesting lets us model an incredible array of information.
Mountain Heights 4
top top
A word wall is a place on your wall where you keep track of the new words and meanings you are learning. You can use a for loop to loop through each element. Pick out the elements' row numbers and column
Write a terminal app that lets you enter new words, and a meaning for each word. numbers.
Your app should have a title bar that says the name of your program. Use two nested for loops to print either an element's symbol or a series of spaces, depending on how full
Your program should give users the option to see all words and meanings that have been entered so that row is.
far.
Your program should give users the option to enter a new word and meaning.
Your program must not allow duplicate entries.
Your program should store existing words and meanings, even after the program closes.
Your program should give users the option to modify an existing meaning.
Bonus Features
Allow users to modify the spelling of words.
Allow users to categorize words.
Turn the program into a game that quizzes users on words and meanings.
(later on) Turn your program into a website that only you can use.
(later on) Turn your program into a website that anyone can register for, and use.
Add a visualization feature that reports on some statistics about the words and meanings that have
been entered.
The Periodic Table (http://www.ptable.com/) of the Elements was developed to organize information about
the elements that make up the Universe. Write a terminal app that lets you enter information about each
element in the periodic table.
Make sure you include the following information:
symbol, name, atomic number, row, and column
Choose at least one other piece of information to include in your app.
Provide a menu of options for users to:
See all the information that is stored about any element, by entering that element's symbol.
Choose a property, and see that property for each element in the table.
Bonus Features
Provide an option to view the symbols arranged like the periodic table. (hint)