Lab: Data Structures#
This lab will give you practice using data structures.
Part 1: An Address Book#
Use data structures to do real work.
1. An Address Book#
There is a file called address_book.txt
it contains the following lines:
Mike, 555-555-1111, 555-555-1112, mike@example.com
Sally, 555-555-1113, 555-555-1114, sally@example.com
Lucia, 555-555-1115, 555-555-1116, lucia@example.com
Mo, 555-555-1117, 555-555-1118, mo@example.com
Read the file, line by line, and insert them into a dictionary called files/address_book
. Each entry in the dictionary should be structured like the example below:
address_book = {
'Mike' : {
'Mobile' : '555-555-1111',
'Office' : '555-555-1112',
'Email' : 'mike@example.com',
},
}
[ ]:
2. Looping Over Data#
Write a for
loop that prints everyone’s mobile number formatted like this:
Contact: Mike Mobile: 555-555-1111
[ ]:
3. Finding Contacts#
Write a program that uses input
to ask the user for the name of a contact. If the contact exists in address_book
print the contact information, otherwise print “Not Found”
[ ]:
Part 2: Wikipedia#
In this part you’ll use Wikipedia’s API to fetch summary information about topics of your choice. You may have noticed that APIs return data with an interesting structure. You’ll have to navigate the structure by using the index operator [ ]
.
1. Get the Summary#
Here’s a function that fetches a data structure from Wikipedia’s API:
[ ]:
import json
import requests
import urllib
def wiki_fetch(title) :
"""Queries Wikipeida using the JSON API and returns the resulting page.
Arguments:
title - (string) The title of the page.
Returns:
The JSON response converted to a dictionary.
"""
safe_title = urllib.parse.quote(title)
url = f'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles={safe_title}'
response = requests.get(url)
data = json.loads(response.text)
return data
Use the wiki_fetch
function to print only the summary for the article on Python (programming language)
[ ]:
2. Get the Summary for Any Article#
Write a program that uses input
to prompt for the name of a Wikipedia article then prints the summary of the article.
[ ]:
3. Handle Errors#
Update the program from 2.2. to print the words “Not Found” when the user types an article that does not have a summary (or doesn’t exist).
[ ]: