Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
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 detailsPublished - Tue, 11 Apr 2023
Sat, 15 Apr 2023
Sat, 15 Apr 2023
Sat, 15 Apr 2023
Write a public review