Advertisement
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)
- # NEW FILE
- # 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]
- # combine all days into a separate "main" list
- temperatures = [temp_day_1, temp_day_2, temp_day_3]
- # raw printing format is mostly used in working life
- # just to quickly check if there's any data at all
- # for any other purpose, it's not usable
- # (because nobody understands what's going on)
- # print(temperatures)
- # loop through each day in the temperatures list
- for day in temperatures:
- print("NEW DAY!")
- # for the current active day,
- # loop through each individual temperature measurement
- # the data as x amount of days, a single day has an y amount of temperatures
- for t in day:
- print(f"{t} ℃")
- print()
- # NEW VERSION OF LIST OF LISTS
- # another version of list of lists
- # product categories in a webstore
- books = ["Lord of the Rings", "Da Vinci Code", "Robinson Crusoe"]
- movies = ["Interstellar", "Forrest Gump", "Jurassic Park"]
- # list of lists => all products split by the categories
- products = [books, movies]
- # since products is a list of lists
- # we need a for loop with another for loop
- for category in products:
- # for each product item in current active 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"
- }
- }
- # printing the whole dictionary is usually a bit too rough
- # to understand what's going on, use indexes instead
- # NOTE! We don't usually need loops with dictionaries
- # Dictionaries are just collections of variables, and they are not
- # # super difficult to use
- # but if you always try to use loops with dictionaries, it's very difficult
- # print(book)
- print(book["name"])
- print()
- # how to use nested dictionaries, in this case, publisher
- # approach 1: save the nested dictionary into a helper variable
- publisher = book['publisher']
- print(publisher['organization'])
- # approach 2: direct chaining also ok
- print(book['publisher']['organization'])
- # NEW FILE
- # our list of dictionaries, products
- products = [
- {"name": "Coffee maker", "price": 79},
- {"name": "Dishwasher", "price": 299},
- {"name": "Freezer", "price": 199},
- {"name": "Toothbrush", "price": 3}
- ]
- # loop through the list of products
- # each product (item) is one dictionary
- # containing name and price
- for item in products:
- print(f"{item['name']} - {item['price']} €")
- # NEW FILE, HOTEL DATA
- 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]
- # just printing hotels the basic way, very hard to see the structure. try var_dump instead
- # print(hotels)
- # vd.var_dump(hotels)
- # first_hotel = hotels[0]
- # vd.var_dump(first_hotel)
- # NEW VERSION
- # use console/terminal and:
- # pip install var_dump
- 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)
- # vd.var_dump(hotels)
- # first_hotel = hotels[0]
- # vd.var_dump(first_hotel)
- # many coders make a comment that helps remembering
- # the data structure FOR A SINGLE ITEM (hotel)
- # [0] => dict(6)
- # ['name'] => str(16) "Snow Line Hotels"
- # ['rating'] => float(4.3)
- # ['wifi'] => bool(True)
- # ['free_breakfast'] => bool(True)
- # ['services'] => list(5)
- # [0] => str(5) "sauna"
- # [1] => str(8) "meetings"
- # [2] => str(10) "restaurant"
- # [3] => str(7) "parking"
- # [4] => str(7) "safaris"
- # ['price_level'] => int(4)
- for hotel in hotels:
- # the structure of each single hotel is described above
- # name of the hotel is easy to get, just print out the variable
- print(hotel['name'])
- # NEW VERSION
- # use the same hotel data is before
- for hotel in hotels:
- # the structure of each single hotel is described above
- # name of the hotel is easy to get, just print out the variable
- print(hotel['name'])
- print("--------------------")
- # services is another list inside a hotel, we need a loop
- # for service in hotel['services']:
- # print(service)
- # since services is just a text list, we have an option -> join() -function
- # this is considered a good practice => it's easy to understand and we avoid
- # one level of for loops
- services = "\n".join(hotel['services'])
- print(services)
- print()
- # NEW VERSION, filtering hotels
- # hotel data same as before
- # create an empty list to catch all matching hotels later in the loop
- restaurant_hotels = []
- for hotel in hotels:
- # the structure of each single hotel is described above
- # name of the hotel is easy to get, just print out the variable
- print(hotel['name'])
- print("--------------------")
- # filter out into a separate list: only hotels that have a restaurant
- if "restaurant" in hotel['services']:
- restaurant_hotels.append(hotel['name'])
- print()
- # just test print the whole list to see if our filtering worked
- print(restaurant_hotels)
- # NEW FILE, actual internet API address, events data
- import urllib.request
- import var_dump as vd
- import json
- # 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")
- # convert the raw JSON (text) into Python data format
- data = json.loads(raw_data)
- # vd.var_dump(data)
- # example of a single event:
- # [0] => dict(4)
- # ['name'] => str(17) "Hub Karaoke Night"
- # ['date'] => str(9) "22.6.2025"
- # ['categories'] => list(3)
- # [0] => str(7) "karaoke"
- # [1] => str(5) "music"
- # [2] => str(13) "participation"
- # ['address'] => dict(2)
- # ['street_address'] => str(16) "Lönnrotinkatu 21"
- # ['postal_code'] => str(5) "00120"
- # all set, let's loop through our events
- for event in data:
- print(event['name'])
- # NEW VERSION
- # use the event data as previously
- # all set, let's loop through our events
- for event in data:
- # print the name of the event
- print(event['name'])
- # get address info into separate variables
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # finally print the address info for the user
- print(f"{postal_code} {street_address}")
- # print the categories also
- categories = ", ".join(event['categories'])
- # since we can't trust this data to always have
- # categories, we have catch this situation
- if len(event['categories']) > 0:
- print(f"CATEGORIES: {categories}")
- else:
- print("-- NO CATEGORIES! --")
- print()
- # VERSION 2, simple search engine: filter only those that match user's choice
- # VERSION 2: simple search engine feature by a category name
- # ONLY SHOW THOSE EVENTS THAT MATCH THE CATEGORY THAT USER SELECTS
- import urllib.request
- import json
- # 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")
- # convert the raw JSON (text) into Python data format
- data = json.loads(raw_data)
- # user's search term for category
- choice = input("What kind of events are you looking for?\n")
- # all set, let's loop through our events
- for event in data:
- # print the categories also
- categories = ", ".join(event['categories'])
- # if the user's choice is not in the categories => SKIP THIS EVENT
- if choice not in categories:
- continue
- # print the name of the event
- print(event['name'])
- # get address info into separate variables
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # finally print the address info for the user
- print(f"{postal_code} {street_address}")
- # since we can't trust this data to always have
- # categories, we have catch this situation
- if len(event['categories']) > 0:
- print(f"CATEGORIES: {categories}")
- else:
- print("-- NO CATEGORIES! --")
- print()
- # NEW VERSION
- # VERSION 3: simple search engine feature by a category name
- # ONLY SHOW THE FIRST EVENT THAT MATCHES UP, forget the rest
- # find one / match one -logic
- # use break-command here!
- import urllib.request
- import json
- # 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")
- # convert the raw JSON (text) into Python data format
- data = json.loads(raw_data)
- # user's search term for category
- choice = input("What kind of events are you looking for?\n")
- # all set, let's loop through our events
- for event in data:
- # print the categories also
- categories = ", ".join(event['categories'])
- # if the user's choice is not in the categories => SKIP THIS EVENT
- if choice in categories:
- # print the name of the event
- print(event['name'])
- # get address info into separate variables
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- # finally print the address info for the user
- print(f"{postal_code} {street_address}")
- # since we can't trust this data to always have
- # categories, we have catch this situation
- if len(event['categories']) > 0:
- print(f"CATEGORIES: {categories}")
- else:
- print("-- NO CATEGORIES! --")
- print()
- # since we found the matching event, stop searching ->
- # break stops the loop instead of processing all the data
- # this adds to better performance for your application
- # (imagine having 200k events, and matching event is found on
- # cycle 254)
- break
- # NEW FILE , exercise 7.5
- 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)
- # you need to find the weakest and strongest winds
- # and their respective cities
- strongest_wind = 0
- strongest_wind_city = ""
- weakest_wind = 0
- weakest_wind_city = ""
- for city in weather:
- print(city['location'])
- # get also the wind value
- wind = city['wind']
- print(wind)
- print()
- # place needed if-statements here to determine
- # strongest and weakest wind
- # NOTE! you can check both weakest and strongest
- # winds in the same for -loop, no need for two!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement