Summary

This document provides an introduction to Python dictionaries. It explains what dictionaries are, how they work, and how to use them. It includes examples, key-value pairs, and common operations. The summary touches on fundamentals of Python and computer science.

Full Transcript

Dictionary Introduction In this module, you'll learn how to use Python's dictionaries, which allow you to connect pieces of related information once it's in a dictionary, and how to modify that information. Because dictionaries can store an almost limitless amount of information, you'll learn how to...

Dictionary Introduction In this module, you'll learn how to use Python's dictionaries, which allow you to connect pieces of related information once it's in a dictionary, and how to modify that information. Because dictionaries can store an almost limitless amount of information, you'll learn how to loop through the data in a dictionary. Additionally, you'll learn to nest dictionaries inside lists, lists inside dictionaries, and even dictionaries inside other dictionaries. Understanding dictionaries allows you to model a variety of real-world objects more accurately. You'll be able to create a dictionary representing a person and then store as much information as you want about that person. You can store their name, age, location, profession, and any other aspect of a person you can describe. You'll be able to store any two kinds of information that can be matched up, such as a list of words and their meanings, a list of people's names and their favorite numbers, a list of mountains and their elevations, and so forth. All of the compound data types we have studied in detail so far — strings, lists, and tuples — are sequential collections. This means that the items in the collection are ordered from left to right and they use integers as indices to access the values they contain. Dictionaries are a different kind of collection. They are Python’s built-in mapping type. A map is an unordered, associative collection. The association, or mapping, is from a key, which can be any immutable type, to a value, which can be any Python data object. As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the keys are strings and the values will also be strings. One way to create a dictionary is to start with an empty dictionary and add key-value pairs. The empty dictionary is denoted {} Dictionary Glossary Dictionary: A collection of key-value pairs that maps from keys to values. The keys can be any immutable type, and the values can be any type. Key: A data item that is mapped to a value in a dictionary. Keys are used to look up values in a dictionary. Key-Value Pair: One of the pairs of items in a dictionary. Values are looked up in a dictionary by key. Mapping Type: A mapping type is a data type composed of a collection of keys and associated values. Python’s only built-in mapping type is the dictionary. Dictionaries implement the associative array abstract data type. Dictionaries Dictionaries are a different kind of collection. They are Python’s built-in mapping type. A map is an unordered, associative collection. The association, or mapping, is from a key, which can be any immutable type, to a value, which can be any Python data object. As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the keys are strings and the values will also be strings. One way to create a dictionary is to start with an empty dictionary and add key-value pairs. The empty dictionary is denoted {} The first assignment creates an empty dictionary named eng2sp. The other assignments new key-value pairs to the dictionary. The left-hand side gives the dictionary and the key being associated. The right-hand side gives the value associated with that key. We can print the current value of the dictionary in the usual way. The key-value pairs of the dictionary are separated by commas. Each pair contains a key and a value separated by a colon. The order of the pairs may not be what you expected. Python uses complex algorithms, designed for very fast access, to determine where the key-value pairs are stored in a dictionary. For our purposes, we can think of this ordering as unpredictable. Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output. It doesn’t matter what order we write the pairs. The values in a dictionary are accessed with keys, not with indices, so there is no need to care about ordering. Here is how we use a key to look up the corresponding value. The key 'two' yields the value 'dos'. Dictionary Operations The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains the names of various fruits and the number of each fruit in stock. If someone buys all of the pears, we can remove the entry from the dictionary. Dictionaries are also mutable. As we’ve seen before with lists, this means that the dictionary can be modified by referencing an association on the left-hand side of the assignment statement. In the previous example, instead of deleting the entry for pears, we could have set the inventory to 0. Similarly, a new shipment of 200 bananas arriving could be handled like this. Notice that there are now 512 bananas—the dictionary has been modified. Note also that the len function also works on dictionaries. It returns the number of key-value pairs: Dictionary Methods Dictionaries have several useful built-in methods. The following table provides a summary and more details can be found in the Python documentation links to an external site.. Method Parameters Description keys none Returns a view of the keys in the dictionary. values none Returns a view of the values in the dictionary. items none Returns a view of the key-value pairs in the dictionary. get key Returns the value associated with the key; None otherwise get key, alt Returns the value associated with the key, alt otherwise. update iterable A dictionary or an iterable object with key-value pairs will be inserted into the dictionary. The keys method returns what Python calls a view of its underlying keys. We can iterate over the view or turn the view into a list by using the list conversion function. It is so common to iterate over the keys in a dictionary that you can omit the keys method call in the for loop — iterating over a dictionary implicitly iterates over its keys. As we saw earlier with strings and lists, dictionary methods use dot notation, which specifies the name of the method to the right of the dot and the name of the object on which to apply the method immediately to the left of the dot. The empty parentheses in the case of keys indicate that this method takes no parameters. The values and items methods are similar to keys. They return view objects which can be turned into lists or iterated over directly. Note that the items are shown as tuples containing the key and the associated value. Note that tuples are often useful for getting both the key and the value at the same time while you are looping. The two loops do the same thing. The in and not in operators can test if a key is in the dictionary: This operator can be very useful since looking up a non-existent key in a dictionary causes a runtime error. The get method allows us to access the value associated with a key, similar to the [ ] operator. The important difference is that get will not cause a runtime error if the key is not present. It will instead return None. There exists a variation of get that allows a second parameter that serves as an alternative return value in the case where the key is not present. This can be seen in the final example below. In this case, since “cherries” is not a key, return 0 (instead of None). Update Method The update() method in Python is used to update the dictionary with elements from another dictionary object or an iterable of key-value pairs. The method adds elements to the dictionary if the key is not already present. If the key exists, the method updates the key with the new value. Here's a quick breakdown of how it works: Syntax: Parameters other: This is the dictionary or iterable containing key-value pairs that will be added to or updated to the existing dictionary. Return Value The method doesn't return any value; it updates the dictionary in place. Examples Updating with another dictionary Note that the value for key 'b' is updated and the new key-value pair 'c': 4 is added. Updating with Key-Value Pairs Updating with Keyword Arguments You can also update the dictionary using keyword arguments: The summary adds new key-value pairs to the dictionary. ​ If keys already exist, update their values. ​ Can accept another dictionary, an iterable of key-value pairs, or keyword arguments to update the dictionary. Performs the update in place and doesn't return a new dictionary. The update() method is a convenient way to update multiple key-value pairs in a dictionary at once, either by merging another dictionary or by adding key-value pairs from an iterable. Aliasing & Copying Introduction In Python, dictionaries are mutable data structures that store key-value pairs. When working with dictionaries, it's important to understand the concepts of aliasing and copying. These concepts determine how multiple references to a dictionary object behave and whether modifications to one reference affect the others. Aliasing: Aliasing refers to the situation where multiple variables refer to the same dictionary object in memory. In other words, they are different names for the same underlying data. Any modification made through one variable will be reflected in all other variables that refer to the same object. Copying: Copying a dictionary involves creating a new and independent dictionary object. Changes made to one dictionary will not affect the other. Python provides different ways to create copies of dictionaries: shallow copying and deep copying. Shallow Copy: Shallow copying creates a new dictionary object, but the values within the dictionary are still references to the original objects. If the original objects are mutable, modifying them may affect both the original and copied dictionaries. Explanation: A shallow copy only copies the outer structure, retaining references to the nested objects. In this case, the inner lists are shared between original and shallow_copied. As a result, changes to the nested elements in shallow_copied (e.g., modifying shallow_copied) are also reflected in the original. Deep Copy: Deep copying creates a completely independent copy of the dictionary and all its nested objects. Modifying the copied dictionary or its values will not affect the original dictionary. Modifications to mutable objects within the deep copied object do not affect the original object, as all objects are fully copied and independent. Understanding the distinction between aliasing and copying is crucial when working with dictionaries in Python. It helps prevent unintended modifications and ensures that modifications are applied where intended. Depending on your needs, you can choose between aliasing or creating shallow or deep copies to suit your specific requirements. Aliasing Aliasing and copying are two different ways to create multiple references to a dictionary object. Understanding the difference between aliasing and copying is important to avoid unintended consequences when working with dictionaries. 1.​ Aliasing: Aliasing occurs when multiple variables refer to the same dictionary object in memory. Any modification made through one variable will be reflected in all other variables that refer to the same object. This is because they are essentially different names for the same underlying data. Imagine you have a dictionary, which is like a box with labeled compartments. Each compartment holds something valuable. Now, imagine you have two different labels (variable names) that point to the same box. Both labels refer to the same box with its compartments. So, if you make changes to the box using one label, the changes will be visible when you look inside the box using the other label. It's like having two different names for the same box. Any modifications made through one name will affect the other name because they are both pointing to the same box. Here's an example of aliasing a dictionary: As you can see from the is operator, alias, and opposites refer to the same object. Copying Now, let's think about making a copy of the dictionary. Instead of having two labels pointing to the same box, you create a new box with the same compartments and put the same valuable items inside. This new box is completely separate from the original one. If you make changes to the new box, it won't affect the original box, and vice versa. It's like having two completely independent boxes with their own sets of valuable items. If you want to modify a dictionary and keep a copy of the original, use the dictionary copy method. Since a copy is a copy of the dictionary, changes to it will not affect the original. Introduction to the join method The join() method in Python is used to concatenate an iterable of strings into a single string, with each string separated by a specified delimiter. Most often, you’ll see it with lists, like this: names = ["Alice", "Bob", "Charlie"] result = ", ".join(names) print(result) # Output: "Alice, Bob, Charlie" ​ Syntax: delimiter. join(iterable) A delimiter is simply a character or sequence of characters used to separate pieces of text. In the context of Python’s.join(), the delimiter is the string you specify that goes between each element of the iterable. For example, if you have a list of names ["Alice", "Bob", "Charlie"] and you call ", ".join(names), then the comma and space (", ") act as the delimiter—separating each name in the final string. ​ Return Value: A string formed by concatenating each element in the iterable with the given delimiter in between. Join & Dictionaries Dictionaries in Python store key-value pairs. They are often used like this: my_dict = { "name": "Alice", "job": "Engineer", "city": "New York" } ​ Keys: ["name", "job", "city"] ​ Values: ["Alice", "Engineer", "New York"] The join() method can operate on any iterable of strings. Therefore, to use join() with dictionaries: 1.​ We often call join() on either my_dict.keys() or my_dict.values(). 2.​ We must ensure the values we’re joining are all strings. If they’re not, we’d need to convert them into strings first. Example: Joining Dictionary Keys my_dict = { "name": "Alice", "job": "Engineer", "city": "New York" } joined_keys = ", ".join(my_dict.keys()) print(joined_keys) # Output: "name, job, city" Example: Joining Dictionary Values my_dict = { "name": "Alice", "job": "Engineer", "city": "New York" } joined_values = ", ".join(my_dict.values()) print(joined_values) # Output: "Alice, Engineer, New York" Note: This works seamlessly here because all the values in my_dict.values() are strings. If any value was an integer or another data type, you’d need to convert it to a string first, e.g.: my_dict = { "name": "Alice", "age": 30, # integer "city": "New York" } joined_values = ", ".join(str(value) for value in my_dict.values()) print(joined_values) # Output: "Alice, 30, New York" Introduction to the Split Method The split() method in Python splits a string into a list of substrings based on a specified delimiter. If no delimiter is provided, Python defaults to splitting on whitespace. string.split(delimiter, max split) ​ delimiter (optional): the character or pattern used to split the string. By default, this is any whitespace. ​ maxsplit (optional): the maximum number of times to split. After the final split, the rest of the string is returned as one piece. ​ Return Value: A list of strings. Example: # Splitting a sentence on spaces sentence = "Hello world from Python" words_list = sentence.split() print(words_list) # ["Hello", "world", "from", "Python"] # Splitting on a comma separated value csv_line = "apple,banana,cherry" fruits_list = csv_line.split(",") print(fruits_list) # ["apple", "banana", "cherry"] Split & Dictionaries While.split() is primarily used on strings, it can be used with dictionaries in a few key ways: 1.​ Splitting Dictionary Values: If a dictionary value is a long string containing multiple pieces of data, you might split that string into a list. 2.​ Parsing a String Into a Dictionary: Sometimes you have a string of key-value pairs. You can split that string into parts and then create a dictionary from it. Splitting Dictionary Values Consider a dictionary where each value is a single string but contains multiple items separated by commas. We can split each value into a list of strings. Example: my_dict = { "fruits": "apple, banana, cherry", "vegetables": "carrot,sspinachkale" } # Splitting the 'fruits' value on commas split_fruits = my_dict["fruits"].split(",") print(split_fruits) # ["apple", "banana", "cherry"] # Splitting the 'vegetables' value split_veggies = my_dict["vegetables"].split(",") print(split_veggies) # ["carrot", "spinach", "kale"] Here, we used.split(",") on each string in the dictionary values to turn them into lists. Parsing a String to Build a Dictionary Another scenario is when we have a single string that contains key-value pairs, and we want to turn this into a dictionary. For example, imagine this string: # Prompt the user for input data_string = input("Enter your key-value pairs in the format: key:value; key:value;...\nExample: name:Alice;job:Engineer;city:New York\n\nYour input: ").strip() # Split the input string on semicolons to separate each "key: value" pair pairs = data_string.split(";") # Create an empty dictionary to store the parsed data parsed_dict = {} For pair in pairs: # For each pair, split on the colon to separate the key from the value key, value = pair.split(":") # Add the key-value pair to the dictionary parsed_dict[key] = value # Print the resulting dictionary print("\nParsed dictionary:") print(parsed_dict) Explanation: ​ Input: We first prompt the user to enter a single string that contains multiple key: value pairs, separated by semicolons (;). ​ Splitting o; - We use split(";") to break the big string into individual key: value pairs. ​ Splitting on: - For each pair, we split again to isolate the key from its corresponding value. ​ Building the Dictionary: We insert each key-value pair into our new dictionary. ​ Output: Finally, we print out the dictionary that was built from the user’s input. Filling a Dictionary with User Input You can prompt for as much input as you need in each pass through a while loop. Let's make a polling program in which each pass-through-the-loop prompts for the participant's name and response. We'll store the data we gather in a dictionary because we want to connect each response with a particular user: The program first defines an empty dictionary (responses) and sets a flag (polling active) to indicate that polling is active. As long as polling_active is True, Python will run the code in the while loop. Within the loop, the user is prompted to enter their name and the mountain they'd like to climb. That information is stored in the response dictionary and the user is asked whether or not to keep the poll running. If they answer yes, the program enters the while loop again. They enter no, the polling_active flag is set to False, the while loop stops running, and the final code block at _____ results of the poll. If you run this program and enter sample responses, you should see the output like this: Looping Through a Dictionary A single Python dictionary can contain just a few key-value pairs or millions of pairs. Because a dictionary can contain large amounts of data, Python lets you loop through a dictionary. Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. You can loop through all of a dictionary's key-value pairs, through its keys, or its values. Looping Through All Key-Value Pairs Before we explore the different approaches to looping, let's consider a new dictionary designed to store information about a user on a website. The following dictionary would store one person's username, first name, and last name: You can access any single piece of information about user_0 based on what you've already learned in this chapter. But what if you wanted to see everything stored in this user's dictionary? To do so, you could loop through the dictionary using a for loop: As shown in line 10, to write a for loop for a dictionary, you create names for the two variables that will hold the key and value in each key-value pair. You can choose any names you want for these two variables. This code would work just as well if you had used abbreviations for the variable names, like this: for (k, v) in user_0.items() The second half of the for statement at line 10 includes the name of the dictionary followed by the method items(), which returns a list of key-value pairs. The for loop then assigns each of these pairs to the two variables provided. In the preceding example, we use the variables to print each key (line 11), followed by the associated value (line 12). The "\n" in the first print() call ensures that a blank line is inserted before each key-value pair in the output: Looping through all key-value pairs works particularly well for dictionaries like the coding language example previously, which stores the same kind of information for many different keys. If you loop through the dictionary, you get the name of each person in the dictionary and their favorite programming language. Because the keys always refer to a person's name and the value is always a language, we'll use the variable name and language in the loop instead of key and value. This will make it easier to follow what's happening inside the loop: The code at line 24 tells Python to loop through each key-value pair in the dictionary. As it works through each pair the key is assigned to the variable name, and the value is assigned to the variable language. These descriptive names make it much easier to see what the print() call at line 25 is doing. Now, in just a few lines of code, we can display all of the information from the poll: This type of looping would work just as well if our dictionary stored the results from polling a thousand or even a million people. Looping Through All the Keys in a Dictionary The keys() method is useful when you don't need to work with all of the values in a dictionary. Let's loop through the favorite_languages dictionary and print the names of everyone who took the poll: Line 39 tells Python to pull all the keys from the dictionary's favorite languages and assign them one at a time to the variable name. The output shows the names of everyone who took the poll: Looping through the keys is the default behavior when looping through a dictionary, so this code would have the same output if you wrote: For name in favorite_languages: Rather than: for name in favorite_languages.keys(): You can choose to use the keys() method explicitly if it makes your code easier to read, or you can omit it if you wish. You can access the value associated with any key you care about 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: At line 44 we make a list of friends that we want to print a message to. Inside the loop, we print each person's name. Then at line 48, we check whether the name we're working with is in the list of friends. If it is, we determine the person's favorite language using the name of the dictionary and the current value of the name as the key (line 49). 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: You can also use the keys() method to find out if a particular person was polled. This time, let's find out if Erin took the poll: The keys() method isn't just for looping: it turns a list of all the keys, and line 54 simply checks if 'Erin' is in this list. Because she's not, a message is printed inviting her to take the poll: Looping Through a Dictionary's Keys in a Particular Order Starting in Python 3.7, looping through a dictionary returns the items in the same order they were inserted. Sometimes, though, you'll want to loop through a dictionary in a different order. One way to do this is to sort the keys as they're returned in the for loop. You can use the sorted() function to get a copy of the keys in order: This statement is like other statements except that we've wrapped the sorted() function around the dictionary.keys() method. This tells Python to list all keys in the dictionary and sort that list before looping through it. The output shows everyone who took the poll, with the names displayed in order: Looping Through All Values in a Dictionary If you are primarily interested in the values that a dictionary contains, you can use the values() method to return a list of values without any keys. For example, say we simply want a list of all languages chosen in our programming language poll without the name of the person who chose each language: The for statement here pulls each value from the dictionary and assigns it to the variable language. When these values are printed, we get a list of all chosen languages: This approach pulls all the values from the dictionary without checking for repeats. That might work fine with a small number of values, but in a poll with a large number of respondents, this would result in a very repetitive list. To see each language chosen without repetition, we can use a set. A set is a collection in which each item must be unique: When you wrap set() around a list that contains duplicate items, Python identifies the unique items in the list and builds a set from those items. At line 72 we use set() to pull out the unique languages in favorite_languages.values(). The result is a nonrepetitive list of languages that have been mentioned by people taking the poll: As you continue learning about Python, you'll often find a built-in feature of the language that helps you do exactly what you want with your data. NOTE: You can build a set directly using braces and separating the elements with commas. It's easy to mistake sets for dictionaries because they're both wrapped in braces. When you see braces but no key-value pairs, you're probably looking at a set. Unlike lists and dictionaries, sets do not retain items in any specific order.

Use Quizgecko on...
Browser
Browser