Where possibilities begin

We’re a leading marketplace platform for learning and teaching online. Explore some of our most popular content and learn something new.
Total 6 Results
Dictionaries in Python

Created by - Robert Kotaki

Dictionaries in Python

 Here's are examples:bashCopy code# Creating a dictionary of a person's information person = {'name': 'John', 'age': 30, 'location': 'New York', 'profession': 'Engineer'} Accessing Values in a DictionaryTo access the value associated with a key, use the key inside a set of square brackets [].bashCopy code# Accessing a person's age from the dictionary print(person['age']) Modifying Values in a Dictionary: We can modify the value of an item in a dictionary by accessing it using its key and then assigning it a new value. Here's an example:Output: ArchitectpythonCopy code# Looping through the person dictionary and printing all the key-value pairs for key, value in person.items(): print(key + ': ' + str(value)) vbnetCopy codename: John age: 30 location: New York profession: Architect Conclusion: Dictionaries are powerful data structures in Python that allow us to store and manipulate related information. We can use them to model real-world objects and situations accurately. With practice, we can become proficient in using dictionaries and harness their full potential in our programs.

More details

Published - Tue, 11 Apr 2023

Adding New Key-Value Pairs

Created by - Robert Kotaki

Adding New Key-Value Pairs

In this lesson, we will learn about adding new key-value pairs to dictionaries in Python. Dictionaries are dynamic structures in Python, and adding new key-value pairs to a dictionary is a straightforward process.Code Examples: Let's take a look at some examples of adding new key-value pairs to a dictionary.Example 1: Suppose we have a dictionary that stores information about a person, such as their name and age. We want to add a new key-value pair to the dictionary that stores their address. Here is the code to accomplish this:pythonCopy codeperson = {'name': 'John', 'age': 30} person['address'] = '123 Main St' print(person) Output:arduinoCopy code{'name': 'John', 'age': 30, 'address': '123 Main St'} In this example, we define a dictionary person that contains the keys 'name' and 'age' and their respective values. We then add a new key 'address' with the value '123 Main St' to the dictionary using square brackets []. Finally, we print the updated dictionary using the print() function.Example 2: Suppose we have a dictionary that stores information about a student's grades. We want to add a new key-value pair to the dictionary that stores their final grade. Here is the code to accomplish this:pythonCopy codegrades = {'math': 90, 'science': 85, 'history': 95} grades['final'] = 92 print(grades) Output:arduinoCopy code{'math': 90, 'science': 85, 'history': 95, 'final': 92} In this example, we define a dictionary grades that contains the keys 'math', 'science', and 'history' and their respective values. We then add a new key 'final' with the value 92 to the dictionary using square brackets []. Finally, we print the updated dictionary using the print() function.Example 3: Suppose we have a dictionary that stores information about a car, such as its make and model. We want to add new key-value pairs to the dictionary that store its color and year. Here is the code to accomplish this:pythonCopy codecar = {'make': 'Toyota', 'model': 'Camry'} car['color'] = 'blue' car['year'] = 2022 print(car) Output:arduinoCopy code{'make': 'Toyota', 'model': 'Camry', 'color': 'blue', 'year': 2022} In this example, we define a dictionary car that contains the keys 'make' and 'model' and their respective values. We then add a new key 'color' with the value 'blue' and a new key 'year' with the value 2022 to the dictionary using square brackets []. Finally, we print the updated dictionary using the print() function.Conclusion: Adding new key-value pairs to a dictionary is a simple and powerful feature of Python dictionaries. By following the examples above, you can add new information to your dictionaries and make them more dynamic and useful for your programming needs.

More details

Published - Tue, 11 Apr 2023

More on Working with Dictionaries in Python

Created by - Robert Kotaki

More on Working with Dictionaries in Python

Starting with an Empty DictionarySometimes it is necessary to start with an empty dictionary and add key-value pairs to it.To create an empty dictionary, use a set of empty braces {}.To add a key-value pair to the dictionary, use the dictionary name followed by square brackets containing the key, and assign it the value.Example:pythonCopy codealien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0) Output: {'color': 'green', 'points': 5}Modifying a Single ValueTo modify a value in a dictionary, we need to use the name of the dictionary followed by the key in square brackets and then assign a new value to that key. For example:pythonCopy codealien_0 = {'color': 'green'} print(f"The alien is {alien_0['color']}.") # The alien is green. alien_0['color'] = 'yellow' print(f"The alien is now {alien_0['color']}.") # The alien is now yellow. In the above code snippet, we first create a dictionary alien_0 with only one key-value pair representing the color of the alien. We print the value of the key 'color', which is 'green'. Then, we modify the value of the key 'color' to 'yellow' and print it again, which gives us 'yellow'.Modifying a Value Using an If-Else BlockIn some cases, we may need to modify the value of a key based on some condition. We can use an if-else block to achieve this. Let's take an example of an alien that can move at different speeds:In the above code snippet, we first create a dictionary alien_0 with three key-value pairs representing the alien's x position, y position, and speed. We print the original x position. Then, we use an if-else block to determine how far the alien should move to the right based on its speed. We assign the result to the variable x_increment. Finally, we modify the value of the key 'x_position' by adding x_increment to it and print the new x position.Here is another example:In this example, we first define a dictionary called person with a 'name' key and an 'age' key. We then use an if-else block to check if the person is over 18 years old. If they are, we modify their age by adding 1 to it using the += operator. We also print a message to indicate that the person's age has been modified.If the person is not over 18 years old, we print a different message indicating that they are not old enough to have their age modified.Note that you can modify any value in a dictionary using this technique, not just the 'age' key as shown in the example. You can also use any condition in the if-else block to determine whether or not to modify the value.You can also use a key to look up a value and modify it at the same time, like this:pythonCopy codealien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} alien_0['x_position'] += 1 alien_0['speed'] = 'fast' Removing Key-Value PairsTo remove a key-value pair from a dictionary, use the del statement followed by the dictionary name and the key in square brackets.Example:pythonCopy codealien_0 = {'color': 'green', 'points': 5} del alien_0['points'] This will remove the key 'points' and its associated value from the dictionary. Be aware that the deleted key-value pair is removed permanently.

More details

Published - Tue, 11 Apr 2023

Using get() to Access Values

Created by - Robert Kotaki

Using get() to Access Values

Introduction: Dictionaries are one of the most useful data structures in Python. They are used to store key-value pairs, where each key is unique and maps to a corresponding value. One common issue when working with dictionaries is that if you try to retrieve a value for a key that doesn't exist, you'll get a KeyError. In this lecture, we'll discuss how to use the get() method to retrieve values from dictionaries in a safer and more efficient way.Section 1: Accessing values using keys To retrieve a value from a dictionary using a key, you can use square brackets [] notation, like this:pythonCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict['key1']) # Output: 'value1' This code will output 'value1', which is the value associated with the key 'key1' in the dictionary.Section 2: The problem with using square brackets One problem with using square brackets to retrieve values from a dictionary is that if you try to access a key that doesn't exist, you'll get a KeyError. For example:pythonCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict['key3']) # Output: KeyError: 'key3' In this case, the key 'key3' doesn't exist in the dictionary, so a KeyError is raised.Section 3: Using the get() method To avoid getting a KeyError when trying to access a non-existent key in a dictionary, you can use the get() method instead of square brackets. The get() method takes two arguments: the key you want to access, and a default value to return if the key doesn't exist. Here's an example:pythonCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict.get('key3', 'default_value')) # Output: 'default_value' In this case, the key 'key3' doesn't exist in the dictionary, so the get() method returns the default value 'default_value', instead of raising a KeyError.Section 4: Using None as a default value If you don't specify a default value for the get() method, it will return None if the key doesn't exist in the dictionary. Here's an example:pythonCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict.get('key3')) # Output: None In this case, the key 'key3' doesn't exist in the dictionary, so the get() method returns None.Another Example on this:Code Example 1: Retrieving a Value Using Square BracketspythonCopy codealien_0 = {'color': 'green', 'speed': 'slow'} print(alien_0['points']) Output:arduinoCopy codeTraceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'points' Explanation: In this example, we are trying to retrieve the value for the key 'points' from the dictionary alien_0 using square brackets. However, since the key 'points' does not exist, a KeyError is raised.Code Example 2: Retrieving a Value Using get()pythonCopy codealien_0 = {'color': 'green', 'speed': 'slow'} point_value = alien_0.get('points', 'No point value assigned.') print(point_value) Output:arduinoCopy codeNo point value assigned. Explanation: In this example, we are using the get() method to retrieve the value for the key 'points' from the dictionary alien_0. The second argument to get() is the default value to return if the key does not exist. In this case, since the key 'points' does not exist, the default value 'No point value assigned.' is returned.Code Example 3: Retrieving a Value Using get() with None as DefaultpythonCopy codealien_0 = {'color': 'green', 'speed': 'slow'} point_value = alien_0.get('points') print(point_value) Output:cssCopy codeNone Explanation: In this example, we are using the get() method to retrieve the value for the key 'points' from the dictionary alien_0. Since we did not provide a second argument to get(), None is returned if the key does not exist.Conclusion: In this lecture, we learned how to use the get() method to retrieve values from dictionaries in a safer and more efficient way. By using the get() method, we can avoid getting a KeyError when trying to access a non-existent key in a dictionary.

More details

Published - Tue, 11 Apr 2023

Looping Through All Key-Value Pairs

Created by - Robert Kotaki

Looping Through All Key-Value Pairs

In this section, we will learn how to loop through all the key-value pairs in a dictionary using a for loop. We will use a simple dictionary to store information about a user on a website to demonstrate the concept.Example DictionaryLet's create a dictionary user_0 that stores the username, first name, and last name of a user on a website.Looping Through All Key-Value PairsTo loop through all the key-value pairs in a dictionary, we can use the items() method. The items() method returns a sequence of key-value pairs in the dictionary.Here is an example of a for loop that uses the items() method to loop through all the key-value pairs in user_0:In this loop, we have created two variables key and value that hold the key and value in each key-value pair. We can use any names we want for these two variables.The first print() statement adds a new line character (\n) to ensure that each key-value pair is printed on a new line. The second print() statement prints the key and value.Here's the output of the loop:We can see that the loop prints all the key-value pairs in the dictionary user_0.Looping Through a Dictionary with Descriptive NamesWe can use descriptive variable names to make our code more readable. Let's use the favorite_languages dictionary from a previous example to demonstrate this concept.In this dictionary, we have stored the favorite programming language of four people.To loop through this dictionary, we can use the items() method and use descriptive variable names name and language to make the code more readable.In this loop, we have assigned the key to the variable name and the value to the variable language. We have used these descriptive names in the print() statement to make the output more readable.Here's the output of the loop:We can see that the loop prints the name of each person in the dictionary and their favorite programming language.ConclusionIn this section, we learned how to loop through all the key-value pairs in a dictionary using a for loop. We used the items() method to loop through the dictionary and assigned descriptive variable names to the key and value in each key-value pair. We also saw how this concept can be applied to a dictionary that stores information about many different keys.

More details

Published - Tue, 11 Apr 2023

Looping Through All the Keys in a Dictionary

Created by - Robert Kotaki

Looping Through All the Keys in a Dictionary

Dictionaries in Python are used to store key-value pairs. In this tutorial, we will discuss how to loop through all the keys in a dictionary using the keys() method in Python.Consider the following dictionary:Looping through all the keys using keys()We can loop through all the keys in a dictionary using the keys() method. The following code shows how to loop through all the keys in favorite_languages dictionary and print the names of everyone who took the poll:This code will produce the following output:Note: Looping through the keys is actually the default behavior when looping through a dictionary, so the following code would have exactly the same output if you wrote:Accessing values associated with keysYou can access the value associated with any key inside the loop, by using the current key. Let's print a message to a couple of friends about the languages they chose. We'll loop through the names in the dictionary as we did previously, but when the name matches one of our friends, we'll display a message about their favorite language:First, we make a list of friends that we want to print a message to. Inside the loop, we print each person’s name. Then we check whether the name we're working with is in the list friends. If it is, we determine the person's favorite language using the name of the dictionary and the current value of name as the key. We then print a special greeting, including a reference to their language of choice.Everyone's name is printed, but our friends receive a special message:Checking if a key is present in a dictionaryYou can also use the keys() method to find out if a particular key is present in a dictionary or not. This time, let's find out if Erin took the poll:The keys() method returns a sequence of all the keys, and the if statement simply checks if 'erin' is in this sequence. Because she's not, a message is printed inviting her to take the poll:In conclusion, the keys() method is a useful tool to loop through all the keys in a dictionary and to check if a key is present in a dictionary.

More details

Published - Tue, 11 Apr 2023

Search
Popular categories
Latest blogs
Tidyverse Package
Tidyverse Package
Tidyverse PackageThe tidyverse package is a collection of packages for data science in R. It includes some of the most frequently used packages, such as dplyr, ggplot2, readr, and tidyr. By installing and loading the tidyverse package, you can load multiple packages at once.InstallationTo install the tidyverse package, use the following command:RCopy codeinstall.packages("tidyverse") Loading PackagesTo load the tidyverse package, use the following command:RCopy codelibrary(tidyverse) This is equivalent to loading the following packages individually:RCopy codelibrary(ggplot2) library(dplyr) library(tidyr) library(readr) library(purrr) library(tibble) library(stringr) library(forcats) Common Inputs and OutputsAll functions in the tidyverse packages are designed to have common inputs and outputs, which are data frames in "tidy" format. This standardization of input and output data frames makes transitions between different functions in the different packages as seamless as possible.For example, the following code demonstrates the use of dplyr and ggplot2 functions on a data frame:RCopy codelibrary(tidyverse) # create a sample data frame data <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6)) # use dplyr to filter data filtered_data <- data %>% filter(x > 1) # use ggplot2 to create a plot ggplot(filtered_data, aes(x, y)) + geom_point() This code filters the data frame to include only rows where x is greater than 1 and then creates a scatter plot of the remaining data using ggplot2.By using the tidyverse package, you can easily move between different packages and functions, making it a powerful tool for data science in R.Lecture Notes: Introduction to the Tidyverse PackageOverviewThe tidyverse package is an "umbrella" package that installs and loads multiple packages at once for you.The tidyverse package includes some of the most frequently used R packages for data science.The tidyverse package is designed to standardize input and output data frames, making transitions between different functions in the different packages as seamless as possible.Installing and Loading the Tidyverse PackageInstall the tidyverse package using install.packages("tidyverse").Load the tidyverse package using library(tidyverse).scssCopy code# Load individual packages library(dplyr) library(ggplot2) library(readr) library(tidyr) # Load tidyverse package library(tidyverse) Common Packages in the Tidyverse Packageggplot2 for data visualizationdplyr for data wranglingtidyr for converting data to “tidy” formatreadr for importing spreadsheet data into RUsing the Tidyverse PackageUse library(tidyverse) to load all the packages in the tidyverse package.Functions in the tidyverse package have common inputs and outputs: data frames are in "tidy" format.For more information, check out the tidyverse.org webpage for the package.scssCopy code# Load tidyverse package library(tidyverse) # Example of using functions in the tidyverse package data(mpg) mpg %>% filter(class == "subcompact") %>% ggplot() + aes(x = displ, y = hwy, color = manufacturer) + geom_point() ConclusionThe tidyverse package is an essential package for data science in R.It includes multiple packages for data visualization, data wrangling, importing data, and converting data to "tidy" format.Loading the tidyverse package is quicker than loading individual packages.The standardization of input and output data frames makes transitions between different functions in the different packages as seamless as possible.

Sat, 15 Apr 2023

Introduction to nycflights13 package and tidy data
Introduction to nycflights13 package and tidy data
Topic: Introduction to nycflights13 package and tidy dataRecall the nycflights13 package we introduced in Section 1.4 with data about all domestic flights departing from New York City in 2013. The package contains several data frames. Let's take a look at the flights data frame.scssCopy code# Load nycflights13 package library(nycflights13) # View the flights data frame View(flights) We saw that flights has a rectangular shape, with each of its 336,776 rows corresponding to a flight and each of its 22 columns corresponding to different characteristics/measurements of each flight. This satisfied the first two criteria of the definition of “tidy” data from Subsection 4.2.1: that “Each variable forms a column” and “Each observation forms a row.”The nycflights13 package also contains other data frames with their rows representing different observational units:airlines: translation between two letter IATA carrier codes and airline company names (16 in total). The observational unit is an airline company.planes: aircraft information about each of 3,322 planes used. i.e. the observational unit is an aircraft.weather: hourly meteorological data (about 8705 observations) for each of the three NYC airports. i.e. the observational unit is an hourly measurement of weather at one of the three airports.airports: airport names and locations. i.e. the observational unit is an airport.The organization of the information into these five data frames follows the third “tidy” data property: observations corresponding to the same observational unit should be saved in the same table i.e. data frame.Case study: Democracy in GuatemalaIn this section, we’ll show you another example of how to convert a data frame that isn’t in “tidy” format (in other words is in “wide” format) to a data frame that is in “tidy” format (in other words is in “long/narrow” format). We’ll do this using the gather() function from the tidyr package again.Furthermore, we’ll make use of functions from the ggplot2 and dplyr packages to produce a time-series plot showing how the democracy scores have changed over the 40 years from 1952 to 1992 for Guatemala.Let’s use the dem_score data frame we imported in Section 4.1, but focus on only data corresponding to Guatemala.scssCopy code# Load required packages library(dplyr) library(tidyr) library(ggplot2) # Select only data corresponding to Guatemala guat_dem <- dem_score %>% filter(country == "Guatemala") # View guat_dem guat_dem We can see that guat_dem is not in “tidy” format. We need to take the values of the columns corresponding to years in guat_dem and convert them into a new “key” variable called year. Furthermore, we need to take the democracy score values in the inside of the data frame and turn them into a new “value” variable called democracy_score.Our resulting data frame will thus have three columns: country, year, and democracy_score. Recall that the gather() function in the tidyr package can complete this task for us:rCopy codeguat_dem_tidy <- guat_dem %>% gather(key = year, value = democracy_score, -country) # View guat_dem_tidy guat_dem_tidy We set the arguments to gather() as follows:key is the name of the variable in the new data frame that will contain the column names of the original data frame

Sat, 15 Apr 2023

Working with Airline Safety Data
Working with Airline Safety Data
Title: Working with Airline Safety DataIntroduction: In this lecture, we will learn how to work with the airline_safety data frame included in the fivethirtyeight data package. We will explore the data, clean it up, and convert it into a tidy format using R programming language.Step 1: Load the dataset We start by loading the airline_safety dataset using the following command:scssCopy codelibrary(fivethirtyeight) data("airline_safety") Step 2: Exploring the dataset We can use the head() and summary() functions to get a quick overview of the dataset.scssCopy codehead(airline_safety) summary(airline_safety) Step 3: Cleaning the dataset We will remove the incl_reg_subsidiaries and avail_seat_km_per_week columns from the dataset using the select() function from the dplyr package.scssCopy codelibrary(dplyr) airline_safety_smaller <- airline_safety %>% select(-c(incl_reg_subsidiaries, avail_seat_km_per_week)) Step 4: Converting to Tidy Format The current format of the data frame is not tidy. We can convert it to tidy format using the tidyr package.scssCopy codelibrary(tidyr) airline_safety_tidy <- airline_safety_smaller %>% pivot_longer( cols = c( incidents_85_99, fatal_accidents_85_99, fatalities_85_99, incidents_00_14, fatal_accidents_00_14, fatalities_00_14 ), names_to = "incident_type_years", values_to = "count" ) Step 5: Viewing the Tidy Dataset We can use the head() function to view the first few rows of the tidy dataset.scssCopy codehead(airline_safety_tidy) Conclusion: In this lecture, we learned how to work with the airline_safety data frame using R programming language. We explored the dataset, cleaned it up, and converted it to tidy format. The resulting dataset is easier to work with and can be used for further analysis.

Sat, 15 Apr 2023

All blogs