Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # TRY THIS IN THE BEGINNING OF LECTURE AND SEE IF IT WORKS:
- # If you get an SSL-error, see Moodle for the "SSL-errors with internet data, HOW TO FIX"
- # If it works okay, you'll see data in raw format in console window
- # If you get an SSL-error, the code is not working as expected
- import urllib.request
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- print(raw_data)
- # UUSI TIEDOSTO
- # collections inside a collection
- temp_day_1 = [13.5, 16.4, 11.6, 11.3]
- temp_day_2 = [12.1, 15.2, 11.9, 10.4]
- temp_day_3 = [15.3, 17.6, 12.5, 11.6]
- # place all day data into a single list
- # => list of lists
- temperatures = [temp_day_1, temp_day_2, temp_day_3]
- # let's loop through the temperatures
- # each day has 4 temperature values
- for day in temperatures:
- print("Processing the next day!")
- # process each temperature in ONE ACTIVE DAY at a time
- for temp in day:
- print(temp)
- print()
- # NEW FILE, another version of list of lists
- # our product categories
- books = ["Lord of the Rings", "Da Vinci Code", "Robinson Crusoe"]
- movies = ["Interstellar", "Forrest Gump", "Jurassic Park"]
- # list of lists => all products splitted by categories
- products = [books, movies]
- # since products is a list of lists
- # we need a for -loop with a for-loop
- for category in products:
- # for each item in this category:
- for item in category:
- print(item)
- # NEW FILE
- # dictionary inside another dictionary
- book = {
- "name": "My Lady Jane",
- "year": 2016,
- "publisher": {
- "name": "HarperTeen",
- "organization": "HarperCollins Publishers",
- "location": "New York"
- }
- }
- # just printing the book with Python is not very readable
- # ok for debugging purposes
- # print(book)
- # getting the name of the book is straight-forward
- print(book['name'])
- # this is usually not enough, since publisher
- # is it's own dictionary
- # print(book['publisher'])
- # let's save the publisher dictionary in its own variable
- publisher = book['publisher']
- print(publisher['location'])
- # one-liner solutions are super common too:
- print(book['publisher']['location'])
- # NEW FILE
- # example, list inside a dictionary
- book = {
- "name": "My Lady Jane",
- "year": 2016,
- "authors": ["Cynthia Hand", "Brodi Ashton", "Jodi Meadows"]
- }
- # get the first author
- # print(book['authors'][0])
- for author in book['authors']:
- print(author)
- # NEW FILE
- # list of dictionaries, the most common combination
- products = [
- {"name": "Coffee maker", "price": 79},
- {"name": "Dishwasher", "price": 299},
- {"name": "Freezer", "price": 199},
- ]
- # products is a list of dictionaries
- # => we need a loop => for each product (p) in products-list
- for p in products:
- name = p['name']
- price = p['price']
- print(f"{name} - {price} €")
- print("All done!")
- print()
- # you can still access by index, for example first product
- first_product = products[0]
- print(first_product['name'])
- # NEW FILE
- # remember to install var_dump first
- # see the materials 3.5 for instructions
- import var_dump as vd
- # create first hotel
- hotel_1 = {
- "name": "Snow Line Hotels",
- "rating": 4.3,
- "wifi": True,
- "free_breakfast": True,
- "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
- "price_level": 4
- }
- # create second hotel
- hotel_2 = {
- "name": "North Ice Hostel",
- "rating": 3.5,
- "wifi": True,
- "free_breakfast": False,
- "services": ["sauna", "parking"],
- "price_level": 2
- }
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- #print(hotels)
- #print()
- #vd.var_dump(hotels)
- # sometimes it's easier to inspect only the first element
- #first_hotel = hotels[0]
- #vd.var_dump(first_hotel)
- for hotel in hotels:
- # print the name of the hotel
- print(hotel['name'])
- # traditional way: just loop through the service list
- # because hotel services is a list, we can just loop:
- # for service in hotel['services']:
- # print(service)
- # a nice trick that works with a list of strings (doesn't work
- # with complex lists though)
- services = ", ".join(hotel['services'])
- print(services)
- print()
- # NEW VERSION
- import var_dump as vd
- # create first hotel
- hotel_1 = {
- "name": "Snow Line Hotels",
- "rating": 4.3,
- "wifi": True,
- "free_breakfast": True,
- "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
- "price_level": 4
- }
- # create second hotel
- hotel_2 = {
- "name": "North Ice Hostel",
- "rating": 3.5,
- "wifi": True,
- "free_breakfast": False,
- "services": ["sauna", "parking"],
- "price_level": 2
- }
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- # loop through all hotels
- for hotel in hotels:
- # print the name of the hotel
- print(hotel['name'])
- # traditional way: loop through services and use if
- # for service in hotel['services']:
- # if service == "restaurant":
- # print("This hotel has a restaurant.")
- # since services is just a list of strings
- # we can use this approach too:
- if "restaurant" in hotel['services']:
- print("This hotel has a restaurant.")
- print()
- # NEW VERSION
- import var_dump as vd
- # create first hotel
- hotel_1 = {
- "name": "Snow Line Hotels",
- "rating": 4.3,
- "wifi": True,
- "free_breakfast": True,
- "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
- "price_level": 4
- }
- # create second hotel
- hotel_2 = {
- "name": "North Ice Hostel",
- "rating": 3.5,
- "wifi": True,
- "free_breakfast": False,
- "services": ["sauna", "parking"],
- "price_level": 2
- }
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- # empty list in the beginning
- # to be filled with hotel names, that contain sauna
- sauna_hotels = []
- # loop through all hotels
- for hotel in hotels:
- # print the name of the hotel
- print(hotel['name'])
- # filtering hotels into a separate list
- # could be used somewhere else
- if "sauna" in hotel['services']:
- sauna_hotels.append(hotel['name'])
- print()
- print(sauna_hotels)
- # NEW FILE, EVENT DATA
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- #vd.var_dump(data)
- # if you want to inspect only the first one:
- #test_event = data[0]
- #vd.var_dump(test_event)
- # data is a list of dictionaries (as implied by var_dump)
- # loop through each event (exact amount varies every day)
- for event in data:
- print(event['name'])
- # NEW VERSION
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- #vd.var_dump(data)
- # if you want to inspect only the first one:
- #test_event = data[0]
- #vd.var_dump(test_event)
- # data is a list of dictionaries (as implied by var_dump)
- # loop through each event (exact amount varies every day)
- for event in data:
- print(event['name'])
- # if we have to take care that address exists before getting postal code:
- # we have do something like this:
- #if "address" in event:
- # postal_code = event['address']['postal_code']
- # if you want to skip the whole event, because of missing data:
- #if "address" not in event:
- # continue
- # get the address information from the dictionary "address"
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # print address info
- print(f"{postal_code} {street_address}")
- # combine categories into one string
- categories = ", ".join(event['categories'])
- # only print categories if there are categories
- # otherwise, inform the user
- if categories != "":
- print(categories)
- else:
- print("-- NO CATEGORIES --")
- print()
- # NEW VERSION, A SIMPLE SEARCH FEATURE -> USER CAN SELECT A CATEGORY
- # ONLY SHOW THOSE EVENTS THAT MATCH THE CATEGORY
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- #vd.var_dump(data)
- # if you want to inspect only the first one:
- # test_event = data[0]
- # vd.var_dump(test_event)
- # ask the user what kind of events they are looking for
- choice = input("Which event category are your searching for?\n")
- # data is a list of dictionaries (as implied by var_dump)
- # loop through each event (exact amount varies every day)
- for event in data:
- # combine categories into one string
- categories = ", ".join(event['categories'])
- # if the user's choice is not in categories -> skip this event
- if choice not in categories:
- continue
- print(event['name'])
- # get the address information from the dictionary "address"
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # print address info
- print(f"{postal_code} {street_address}")
- # only print categories if there are categories
- # otherwise, inform the user
- if categories != "":
- print(categories)
- else:
- print("-- NO CATEGORIES --")
- print()
- # NEW VERSION, only look for the FIRST ENTRY that matches in the data
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- #vd.var_dump(data)
- # if you want to inspect only the first one:
- # test_event = data[0]
- # vd.var_dump(test_event)
- # ask the user what kind of events they are looking for
- # only show the first match in data
- choice = input("Which event category are your searching for?\n")
- # data is a list of dictionaries (as implied by var_dump)
- # loop through each event (exact amount varies every day)
- for event in data:
- # combine categories into one string
- categories = ", ".join(event['categories'])
- # if user's choice is in the categories
- if choice in categories:
- print(event['name'])
- # get the address information from the dictionary "address"
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # print address info
- print(f"{postal_code} {street_address}")
- # only print categories if there are categories
- # otherwise, inform the user
- if categories != "":
- print(categories)
- else:
- print("-- NO CATEGORIES --")
- print()
- break
- # NEW FILE
- import json
- import urllib.request
- url = "https://edu.frostbit.fi/api/weather/"
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- weather = json.loads(raw_data)
- # initialize variables needed in the loop
- strongest_wind = 0
- strongest_wind_city = ""
- weakest_wind = 0
- weakest_wind_city = ""
- # because weather is a list of dictionaries:
- # remember: you only need one loop to process both weakest and strongest wind
- for city in weather:
- print(city['location'])
- print(city['wind'])
- # if current city wind is bigger than previous wind (strongest_wind)
- # set the current wind as the strongest_wind
- # also save down the name of the city (strongest_wind_city)
- print()
Add Comment
Please, Sign In to add comment