CHAPTER 11

Working with Lists and Dictionaries

Python provides lists and dictionaries for storing data efficiently in variables. A list is a collection that can store multiple items of the same type or of different types and provides access to its items via an index. A dictionary is similar to a list but more powerful, allowing you to create collections of information that you access through named elements called keys.

Snapshot of working with lists and dictionaries.

Understanding Lists and Their Use

Create a List

Meet Python’s List Methods

Add Items to a List

Remove Items from a List

Locate Items and Access Data in a List

Sort the Items in a List

Understanding Dictionaries and Their Use

Create a Dictionary and Return Values

Meet Python’s Dictionary Methods

Create a Dictionary from an Existing Iterable

Add Key/Value Pairs to a Dictionary

Remove Key/Value Pairs from a Dictionary

Return Keys and Values from a Dictionary

Understanding Lists and Their Use

In Python, a list is an object that enables you to store multiple items within a single variable. The items can be of the same type or of different types. The list contains an index that enables you to set or retrieve the individual items. Technically, a list is a mutable sequence, so you can change the order of its items, add and remove items, sort the items, and so on.

A List Is Ordered and Indexed

In Python, a list is an ordered and indexed collection:

  • Ordered. The items in a list appear in the order you set. You can change the order by adding items, removing items, or reversing the order.
  • Indexed. The list items are indexed using zero-based numbering, so the first list item is item 0, the second item is item 1, and so on. You use the index numbers to access the list items.

List Items Are Mutable

The items in a list are mutable, so you can change a list after creating it. For example, you can add items to a list, remove items from it, or reverse its order.

Lists Can Contain Duplicate Values

A list can contain duplicate values, as there is no constraint requiring each value to be unique.

You can use the count() method to count the number of items in a list that have a particular value.

Understanding How Lists Compare to Tuples and Sets

Table 11-1 summarizes the three key attributes of lists, tuples, and sets in Python.

Table 11-1: Attributes of Lists, Tuples, and Sets

Collection

Mutable

Ordered

Duplicates Allowed

List

Yes

Yes

Yes

Set

Yes

No

No

Tuple

No

Yes

Yes

Understanding How Lists Compare to Sets

In Python, both a list and a set can contain various types of data, which gives you great flexibility at the risk of occasionally running into the wrong data type for your needs. Beyond that, however, lists differ significantly from sets.

First, a list is ordered, while a set is unordered. Second, a list can contain duplicates, whereas a set cannot contain duplicates. Third, and more technically, Python sets use hashing to store their values, which makes lookups in sets fast and efficient but means the order of a set’s items may vary.

Understanding How Lists Compare to Tuples

The key difference between a list and a tuple is that a list is mutable whereas a tuple is immutable. Both lists and tuples are ordered and can contain duplicate items. Both lists and tuples are sequential, which enables you to iterate through the items they contain.

Tuples’ immutability means that they are more memory efficient than lists and require less processing time. When your code contains data that will not need to be changed, you may be able to improve performance by using tuples rather than lists.

Understanding How Python Lists Compare to Arrays in Other Programming Languages

Python lists are similar to arrays in other programming languages, but lists offer greater flexibility. There are two main differences between lists and arrays.

First, when you create an array, you specify its data type, such as float; the array can contain only items that have that data type. By contrast, a list in Python can contain items of different data types, as needed.

Second, when you create an array, you specify the number of items it contains. Python allocates memory to store each potential item, but you do not need to populate each item immediately, or indeed ever. By contrast, a list’s size is dynamic, increasing as items are added, but each item must contain data, even if the data type is None.

Create a List

To create a list, you declare a variable; enter the assignment operator, =; and then enter the list items, separated by commas, within square brackets. For example, the statement list1 = [1, 2, 3] declares a variable named list1 and assigns to it three integers — 1, 2, and 3.

In this section, you create three lists in a terminal window. The first list contains integers, the second list contains strings, and the third list contains four different data types.

Create a List

Snapshot of create a list.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named list1 and assigns five integers to it, and then press Ent:

list1 = [1, 2, 3, 4, 5]

003.eps Type the following statement, which uses the print() function to display the contents of list1, and then press Ent:

print(list1)

Python displays [1, 2, 3, 4, 5]. The brackets indicate that the variable’s contents are a list.

“Snapshot of the following statement, which creates a variable named list2.”

004.eps Type the following statement, which creates a variable named list2 and assigns two strings to it, and then press Ent:

list2 = ["Evie", "Frank"]

005.eps Type the following statement, which creates a variable named list3 and assigns several kinds of data to it. Press Ent.

list3 = [11.5, "cats", True, 0]

006.eps Type the following statement to display the contents of list2. Press Ent.

print(list2)

Python displays ['Evie', 'Frank'].

007.eps Type the following statement to display the contents of list3. Press Ent.

print(list3)

Python displays [11.5, 'cats', True, 0].

Meet Python’s List Methods

Python provides 11 methods for working with lists. Three of these methods — append(), extend(), and insert() — enable you to add items to the list. Conversely, three other methods — clear(), pop(), and remove() — enable you to remove one or all methods from the list. The other five methods enable you to sort the list, return an element by its position in the list, return the number of items that match specific criteria, and create a copy of the list.

Table 11-2 explains Python’s methods for working with lists.

Table 11-2: Methods for Working with Lists

Method

Use This Method To

append()

Add an element to the end of the list.

clear()

Remove all the elements from the list.

copy()

Create a copy of the list.

count()

Count the number of list elements that match the specified value.

extend()

Extend the list by adding the elements from another list or other iterable.

index()

Return the index number of the first list element that matches the specified value.

insert()

Insert an element in the list at the specified index position.

pop()

Remove the list element at the specified index position.

remove()

Remove the first list element that matches the specified value.

reverse()

Reverse the order of the whole list.

sort()

Sort the list in ascending order, descending order, or ordered by the function specified.

The following list provides examples of using these methods. You will use the methods more extensively during the first half of this chapter.

  • Create a list named list4 and a list named list5:

    list4 = ["Brian", "Charlene", "Dan"]

    list5 = ["Eva", "Finn"]

  • Insert an item at the first index position in the list list4:

    list4.insert(0, "Abigail")

  • Extend the list list4 by adding the elements from list5:

    list4.extend(list5)

  • Add the item Gloria to the end of the list list4:

    list4.append("Gloria")

  • Sort the list list4 alphabetically:

    list4.sort()

  • Remove the second item from the list list4:

    list4.pop(1)

  • Remove all the items from the list list4:

    list4.clear()

Add Items to a List

Python’s lists are mutable, so you can change a list after creating it. Often, you will want to add items to the list, as explained here, or remove items from it, as explained in the following section, “Remove Items from a List.” You can use the append() method to add a single element to the end of a list, use the insert() method to insert an item at a specific index position in the list, or use the extend() method to extend the list by adding items from another list or from another iterable element.

Add Items to a List

Snapshot of add items to a list.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates the variable n1 and assigns a list of two strings to it. Press Ent.

n1 = ["Sam", "George"]

003.eps Type the following print() statement, and then press Ent, to display the contents of n1:

print(n1)

Snapshot of type the following print statement.

Python displays ['Sam', 'George'].

004.eps Type the following statement, which creates the variable n2 and assigns a list of two other strings to it. Press Ent.

n2 = ["Antonia", "Brett"]

005.eps Type the following print() statement, and then press Ent, to display the contents of n2:

print(n2)

Python displays ['Antonia', 'Brett'].

006.eps Type the following statement, which uses the insert() method to insert a string at position 1 — second — in n1. Press Ent.

n1.insert(1, "Helen")

“Snapshot of the following statement, which uses the extend.”

007.eps Press Arkup four times, making Python enter the print(n1) statement again, and then press Ent.

print(n1)

Python displays ['Sam', 'Helen', 'George'].

008.eps Type the following statement, which uses the extend() method to add n2 to the end of n1, and then press Ent:

n1.extend(n2)

009.eps Press Arkup twice to enter the print(n1) statement once more, and then press Ent:

print(n1)

Python displays ['Sam', 'Helen', 'George', 'Antonia', 'Brett'].

Snapshot of enter the statement.

010.eps Type the following statement, which uses the append() method to add a string to the end of n1, and then press Ent:

n1.append("Sia")

011.eps Press Arkup twice to enter the print(n1) statement yet again, and then press Ent.

print(n1)

Python displays ['Sam', 'Helen', 'George', 'Antonia', 'Brett', 'Sia'].

Remove Items from a List

Python provides three methods for removing items from a list. When you need to remove a single item by specifying its index position, use the pop() method. When you need to remove the first item that matches the value you specify, use the remove() method; you may then need to check for other instances of the item in the list and remove them too if necessary. When you need to remove all the items from the list, use the clear() method.

Remove Items from a List

Snapshot of remove items from a list.

001.eps In Visual Studio Code, create a new script, and then save it.

002.eps Type the following statement, which creates a variable named dx and assigns to it a list of integers. Press Ent.

dx = [1, 3, 4, 4, 4, 5, 7, 4, 8, 4, 11]

003.eps Type the following statement, which uses the print() function to display a string giving the number of instances of 4 in the list. Press Ent.

print("The list contains " + str(dx.count(4)) + " instances of 4.")

004.eps Type the following statement, which uses the index() method to return the position of the first 4 in the dx list and the print() function to display a string announcing its removal. Press Ent.

print("Removing the 4 at index position " + str(dx.index(4)) + ".")

Snapshot of the following statement, which uses the pop.

005.eps Type the following statement, which uses the pop() method of the dx list to remove the first 4 by specifying its index position. Press Ent.

dx.pop(dx.index(4))

006.eps Type the following statement, which starts a while loop that runs while the count() method returns more than one 4 in the dx list. Press Ent.

while dx.count(4) > 1:

007.eps Copy the step 4 statement and paste it onto the line after the while line, accepting the indent that Visual Studio Code automatically applies.

print("The list contains " + str(dx.count(4)) + " instances of 4.")

“Snapshot of the following statement, which uses the remove.”

008.eps Type the following statement, which creates a variable called msg and assigns to it a string announcing the removal of the 4 at the index position it specifies. Press Ent.

msg = "Removing the 4 at index position " + str(dx.index(4)) + "."

009.eps Type the following statement, which uses the remove() method to remove the first instance of 4 from dx. Press Ent.

dx.remove(4)

010.eps Type the following statement, which uses the print() function to display msg. Press Ent.

print(msg)

Snapshot of the terminal pane appears.

011.eps Press Bksp to remove the indent, ending the while block, and then type the following statement to display the contents of dx. Press Ent.

print(dx)

012.eps Type the following statement, which uses the clear() method to remove the contents of dx. Press Ent.

dx.clear()

013.eps Type the following statement to display the contents of dx — nothing.

print(dx)

014.eps Click Run Python File in Terminal (9781119860259-ma040).

The Terminal pane appears.

dga.eps The print() statements display the output as the while loop whittles down the instances of 4 until only one remains.

Locate Items and Access Data in a List

Often, you will need to determine whether a list contains a particular item and, if it does, where that item is. Python provides the count() method and the index() method to take care of this need. You use the count() method to return an integer value giving the number of elements in the list that match a specified value. If this number is greater than 0, you can use the index() method to return the index number of the first item in the list that matches your specified value.

Locate Items and Access Data in a List

Snapshot of python prompt appears.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named scores and assigns to it a list containing several integers. Press Ent.

scores = [20, 15, 40, 48, 15, 8]

003.eps Type the following statement, which uses the len() function to return the number of items in the scores list. Press Ent.

print(len(scores))

Snapshot of python displays 6, the number of items.

Python displays 6, the number of items.

004.eps Type the following statement, which uses the count() method to determine the number of instances of 15 in scores, and then press Ent:

scores.count(15)

Python returns 2, because the scores list contains two instances of 15.

005.eps Type the following statement, which uses the index() method to return the index position of the first instance of 15 in the list. Press Ent.

scores.index(15)

Snapshot of python displays 0.

Python returns 1, indicating that the first instance of 15 is at index position 1 in the list — in other words, it is the second item.

006.eps Type the following statement, which uses the count() method to determine the number of instances of 36 in scores, and then press Ent:

scores.count(36)

Python displays 0, because the scores list contains no instances of 36.

Snapshot of python returns an error.

007.eps Type the following statement, which uses the index() method to return the index position of the first instance of 36 in the list. Press Ent.

scores.index(36)

dgb.eps Python returns an error: ValueError: 36 is not in list.

Sort the Items in a List

Python provides two methods for sorting the items in a list. The reverse() method simply reverses the current sort order of the list, so if you have a list named names1 that contains ["Alex", "Blake", "Cody"), names1.reverse() returns ["Cody", "Blake", "Alex"]. The sort() method is more widely useful, enabling you to sort a list in ascending order, in descending order, or in the order given by a function you specify.

Sort the Items in a List

Snapshot of sort the items in a list.

Sort Using the sort() Method and the reverse() Method

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named k7 and assigns a list of three fruits to it. Press Ent.

k7 = ["tomato", "avocado", "okra"]

003.eps Type the following statement, which sorts the k7 list into ascending order, and then press Ent:

k7.sort()

“Snapshot of the following statement, which displays the contents of k7.”

004.eps Type the following statement, which displays the contents of k7, and then press Ent:

print(k7)

Python displays ['avocado', 'okra', 'tomato'].

005.eps Type the following statement, which use the reverse argument to sort the k7 list in descending order, and then press Ent:

k7.sort(reverse = True)

006.eps Press Arkup twice to repeat the print(k7)statement, and then press Ent:

print(k7)

Python displays ['tomato', 'okra', 'avocado'].

“Snapshot of the following statement, which uses the reverse.”

007.eps Type the following statement, which uses the reverse() method to reverse the list’s order, and then press Ent:

k7.reverse()

008.eps Press Arkup twice to repeat the print(k7) statement again, and then press Ent.

print(k7)

Python displays ['avocado', 'okra', 'tomato'] again.

“Snapshot of sort using a function that provides sort criteria.”

Sort Using a Function That Provides Sort Criteria

001.eps Type the following function, which implements a crude sort by the last character of the input. Press Ent at the end of each line, and then again to end the function and create a blank line.

def sort_by_last(n):

return n[-1]

Note: Indent the second line by four spaces.

002.eps Type the following statement, which creates a variable named animals and assigns a list of three animals to it. Press Ent.

animals = ["cat", "dog", "snake"]

003.eps Type the following statement, which uses the sort() method to sort the animals list by the sort_by_last function. Press Ent.

animals.sort(key=sort_by_last)

004.eps Type a print() statement to display the contents of animals, and then press Ent:

print(animals)

Python displays ['snake', 'dog', 'cat'], the terms sorted by their last letters.

Understanding Dictionaries and Their Use

In Python, a dictionary is an object that enables you to store collections of data. The items in the dictionary consist of key/value pairs, in which a key enables you to access the corresponding value — similar in concept to a conventional dictionary, in which you look up a term to find its meaning.

Technically, a dictionary is an ordered, mutable sequence, so you can add items, remove specific items, or simply delete the entire contents of the dictionary.

Understanding What Python Dictionaries Are

In Python, a dictionary is an ordered, mutable collection that cannot have duplicates:

  • Ordered. The items in a dictionary have a specific order, which Python maintains.
  • Mutable. A dictionary is mutable, so you can change its contents. For example, you can add items to the dictionary or remove items from it.
  • No duplicates. Each key in the dictionary must be unique so that you can identify each key unambiguously. However, the values assigned to the keys can contain duplicates.

Understanding the Layout of a Python Dictionary

To create a dictionary, you enter its key/value pairs within braces, {}. Usually, you assign the entire dictionary to a variable so that you can refer to it easily. For example, the following statement creates a variable named dog0 and assigns to it a dictionary consisting of a single key/value pair, the key being name and the value being Spot:

dog0 = {"name": "Spot"}

Snapshot of understanding the layout of a python dictionary.

You can create a dictionary on a single line of code, as in the following example, which shows a single logical line wrapped to multiple physical lines by the constraints of the book.

dog1 = {"name": "Minnie", "breed": "Chihuahua", "weight": 5, "height": 6, "age": 6}

Normally, however, it is more convenient to break the dictionary over multiple lines of code, using the kind of layout shown in the following example:

dog2 = {

"name": "Max",

"breed": "Newfoundland",

"weight": 130,

"height": 30,

"age": 4

}

“Snapshot of using the kind of layout.”

Here, each key — name, breed, and so on — appears on a separate line followed by a colon and its value, making the code easier to read quickly.

You Access Dictionary Items by Key

To access an item in a dictionary, you specify the item’s key. For example, to access the value for the breed key in the dog2 dictionary, you specify dog2["breed"].

Dictionaries Are Ordered in Python 3.7 Onward

Python 3.7 changed dictionaries from unordered collections to ordered collections. If you are using Python 3.6 or an earlier version, your code’s dictionaries will be unordered — that is, the items in a dictionary will be in an order, but that order will not be fixed.

As long as you access your dictionary items by key, it makes little difference whether the dictionary items are ordered or unordered. But if you access your dictionary items by index position — for example, by creating a list of the dictionary’s keys and using that to determine a key’s position — you should be aware of the difference, because in Python 3.6 or earlier the items’ index positions are likely to change.

Create a Dictionary and Return Values

When you need to store data in a container that enables you to look up elements of the data quickly and easily, create a dictionary and assign it to a variable. You enter the entire dictionary within braces, {}, using a colon to connect each key to its value and a comma to separate each key/value pair from the next pair.

You can then either display the entire dictionary — for example, to verify its contents and completeness — or return individual values by specifying their keys.

Create a Dictionary and Return Values

Snapshot of create a dictionary and return values.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named dog3 and assigns to it a dictionary containing several canine attributes. Press Ent at the end of each line.

dog3 = {

"name": "Belle",

"breed": "Rottweiler",

"weight": 125,

"height": 26,

"age": 8

}

“Snapshot of python displays the dictionary’s keys and values on a single logical line.”

003.eps Type the following statement, which uses the print() function to display the entire dog3 dictionary. Press Ent.

print(dog3)

Python displays the dictionary’s keys and values on a single logical line, wrapped here:

{'name': 'Belle', 'breed': 'Rottweiler', 'weight': 125, 'height': 26, 'age': 8}

004.eps Type the following statement, which uses the print() function to display the breed key from the dog3 dictionary. Press Ent.

print(dog3["breed"])

Python displays Rottweiler.

Meet Python’s Dictionary Methods

Python provides 11 methods for working with dictionaries. Five of these methods — fromkeys(), get(), items(), keys(), and values() — enable you to retrieve information from a dictionary. On the other side of the coin, three methods — pop(), popitem(), and clear() — enable you to remove one or more entries from the dictionary. One method, update(), lets you insert key/value pairs. One method, setdefault(), does double duty, returning information if it is there and adding it if it is not. Finally, the copy() method enables you to copy an entire dictionary.

Table 11-3 explains Python’s methods for working with dictionaries.

Table 11-3: Methods for Working with Dictionaries

Method

Use This Method To

clear()

Remove all the key/value pairs from the dictionary.

copy()

Create a copy of the entire dictionary.

fromkeys()

Return a dictionary containing the specified keys and their values from this dictionary.

get()

Return the value of the specified key.

items()

Return a list containing a tuple for each key/value pair in the dictionary.

keys()

Return a list of the dictionary’s keys, without their values.

pop()

Remove the items whose key you have specified.

popitem()

Remove the last key/value pair inserted in the dictionary.

setdefault()

Return the value of the specified key, if it exists; if it does not exist, insert the key and assign it the specified value.

update()

Insert the specified key/value pairs in the dictionary.

values()

Return a list of all the dictionary’s values.

The following list provides quick examples of using these methods. You will use the methods more extensively during the remainder of this chapter:

  • Return the keys from the dog3 dictionary:

    >>> dog3.keys

    dict_keys(['name', 'breed', 'weight', 'height', 'age'])

  • Insert a key/value pair, with the key id_chip, in the dog3 dictionary:

    >>> dog3.update({"id_chip": "yes"})

  • Return the value of the key coat, if it exists, and assign the given value if the key does not exist. In the first instance, the key does not exist, so Python creates it and assigns the value provided. In the second instance, the key exists, so Python returns the current value.

    >>> dog3.setdefault("coat", "short")

    'short'

    >>> dog3.setdefault("coat", "long")

    'short'

Create a Dictionary from an Existing Iterable

Python’s fromkeys() method enables you to create a dictionary whose keys come from an existing iterable, such as a list, a set, or another dictionary. This way of creating a dictionary is convenient when you have an iterable that contains the data required for the keys in a new dictionary you want to create. The fromkeys() method lets you either assign the same value to each of the key/value pairs or not assign a value, leaving the values blank until you populate them otherwise.

Create a Dictionary from an Existing Iterable

Snapshot of create a dictionary from an existing iterable.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named pet_factor and assigns to it a list of factors to consider when choosing a pet. Press Ent.

pet_factor = ["space", "character", "cost", "interactivity"]

“Snapshot of the following statement, which uses the print function.”

003.eps Type the following statement, which creates a variable named considerations and assigns to it a dictionary whose keys are derived by using the fromkeys() method on the pet_factor list. Press Ent.

considerations = dict.fromkeys(pet_factor)

004.eps Type the following statement, which uses the print() function to display the contents of considerations. Press Ent.

print(considerations)

Python displays {'space': None, 'character': None, 'cost': None, 'interactivity': None}.

Note: Each key contains the value None because the fromkeys() method in step 3 did not assign a value to the keys.

“Snapshot of the following statement, which creates a variable called cat.”

005.eps Type the following statement, which creates a variable named pet_pros and assigns to it a list of benefits of having a pet. Press Ent.

pet_pros = ["companionship", "affection", "exercise", "memory", "schedule"]

006.eps Type the following statement, which creates a variable called cat and assigns to it a dictionary whose keys are derived by using the fromkeys() method on the pet_pros list. The statement assigns a default value of True to each key. Press Ent.

cat = dict.fromkeys(pet_pros, True)

“Snapshot of the following print statement to display the contents of cat.”

007.eps Type the following print() statement to display the contents of cat, and then press Ent:

print(cat)

Python displays {'companionship': True, 'affection': True, 'exercise': True, 'memory': True, 'schedule': True}.

You can now change the values of the keys, as needed.

Add Key/Value Pairs to a Dictionary

When you need to add one or more key/value pairs to a dictionary, use the update() method. You can either add the key/value pairs by providing their information directly or add them from an iterable object — for example, from another dictionary. The update() method places the new key/value pairs at the end of the dictionary.

You can also add a key/value pair to a dictionary by using the setdefault() method. If the key/value pair already exists, this method returns the current value. If the key/value pair does not exist, this method creates the pair and assigns the value you provide.

Add a Key/Value Pair to a Dictionary

Snapshot of add a key value pair to a dictionary.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named dog4 and assigns to it a dictionary containing a single key/value pair. Press Ent.

dog4 = {"name": "Rex"}

003.eps Type the following statement, which uses the update() method to add one key/value pair to dog4, and then press Ent:

dog4.update({"breed": "Newfoundland"})

“Snapshot of the following update statement, which adds two more key value pairs.”

004.eps Type the following print() statement, and then press Ent:

print(dog4)

Python displays {'name': 'Rex', 'breed': 'Newfoundland'}.

005.eps Type the following update()statement, which adds two more key/value pairs, and then press Ent:

dog4.update({"age": 5, "color": "black"})

006.eps Press Arkup twice to enter the print() statement again, and then press Ent:

print(dog4)

Python displays {'name': 'Rex', 'breed': 'Newfoundland', 'age': 5, 'color': 'black'}}.

007.eps Type the following statement, which creates a variable named stats and assigns it a dictionary containing two key/value pairs. Press Ent.

stats = {"height": 28, "weight": 146}

“Snapshot of the following statement, which uses the update method.”

008.eps Type the following statement, which uses the update() method to insert the key/value pairs from stats into dog4. Press Ent.

dog4.update(stats)

009.eps Press Arkup thrice to enter the print() statement again, and then press Ent:

print(dog4)

Python displays {'name': 'Rex', 'breed': 'Newfoundland', 'age': 5, 'color': 'black', 'height': 28, 'weight': 146}.

010.eps Type the following statement, which uses the setdefault() method to return the value of the breed key, if it exists, and to create the key/value pair if it does not. Press Ent.

dog4.setdefault("breed")

Python returns 'Newfoundland', because the breed key does exist.

“Snapshot of python returns newfoundland, because the breed key does exist.”

011.eps Type the following statement, which uses the setdefault() method to return the value of the temperament key, if it exists, and to create the key/value pair if it does not. Press Ent.

dog4.setdefault("temperament", "amiable")

Python returns 'amiable', which tells you that the temperament key’s value is amiable.

012.eps Type the following print() statement, which displays the temperament key’s value, and then press Ent:

print(dog4["temperament"])

Python displays amiable.

Remove Key/Value Pairs from a Dictionary

Python provides three methods that enable you to remove key/value pairs from a dictionary. First, you can use the pop() method to remove an item by specifying its key. Second, you can use the popitem() method to remove the last key/value pair that was added to the dictionary; because Python places the newest key at the end of the dictionary, this method removes the last key and its value. Finally, you can use the clear() method to remove all keys and their values from the dictionary, leaving the dictionary empty.

Remove Key/Value Pairs from a Dictionary

Snapshot of remove key value pairs from a dictionary.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement, which creates a variable named ocelot and assigns to it a dictionary containing eight key/value pairs. Press Ent.

ocelot = {

… "Kingdom": "Animalia",

… "Phylum": "Chordata",

… "Class": "Mammalia",

… "Order": "Carnivora",

… "Suborder": "Feliformia",

… "Family": "Felidae",

… "Subfamily": "Felinae",

… "Genus": "Leopardus"

… }

“Snapshot of the following statement, which uses the popitem.”

003.eps Type the following statement, which uses the popitem() method to remove the last key/value pair. Press Ent.

ocelot.popitem()

Python displays ('Genus', 'Leopardus') to indicate that it has removed the Genus key, whose value was Leopardus.

Note: In Python versions 3.6 and earlier, the popitem() method removes a random key/value pair from the dictionary rather than the last pair.

004.eps Type the following statement, which uses the popitem() method again but this time assigns the resulting tuple to a variable named y. Press Ent.

y = ocelot.popitem()

“Snapshot of the following statement, which uses the pop.”

005.eps Type the following print() statement to display the contents of y. Press Ent.

print(y)

Python displays ('Subfamily', 'Felinae').

006.eps Type the following statement, which uses the pop() method to remove the Class key, and then press Ent:

ocelot.pop("Class")

Python displays 'Mammalia' to indicate the value that was assigned to the key it has removed.

007.eps Type the following print() statement to display the contents of the ocelot dictionary as they now stand. Press Ent.

print(ocelot)

“Snapshot of the following statement, which uses the clear method.”

Python displays {'Kingdom': 'Animalia', 'Phylum': 'Chordata', 'Order': 'Carnivora', 'Suborder': 'Feliformia', 'Family': 'Felidae'}.

008.eps Type the following statement, which uses the clear() method to remove the dictionary’s contents, and then press Ent.

ocelot.clear()

009.eps Press Arkup twice to enter the print() statement again, and then press Ent:

print(ocelot)

Python displays {}, indicating that the dictionary is empty.

Return Keys and Values from a Dictionary

You can return a value from a dictionary by entering the corresponding key’s name in brackets after the dictionary’s name — for example, dog1["breed"] returns the value of the breed key in the dictionary called dog1. Alternatively, you can use the get() method to return the value for a specific key.

You can use the keys() method to return all of a dictionary’s keys, use the values() method to return all its values, or use the items() method to return both the keys and the values. These three methods return views that update automatically when the dictionary’s contents change.

Return Keys and Values from a Dictionary

Snapshot of return keys and values from a dictionary.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following statement to create a variable called dog5 and assign to it a dictionary containing a canine’s key attributes. Press Ent.

dog5 = {

… "name": "Hondje",

… "breed": "Boerboel",

… "height": 24,

… "weight": 70

… }

“Snapshot of the following statement, which uses the keys method.”

003.eps Type the following statement, which uses the get() method to return the value of the breed key. Press Ent.

dog5.get("breed")

Python returns 'Boerboel'.

004.eps Type the following statement, which uses the keys() method and displays all the keys in the dog5 dictionary, and then press Ent:

print(dog5.keys())

Python displays dict_keys(['name', 'breed', 'height', 'weight']).

Note: The keys() method returns a list containing the keys. Similarly, the values() method returns a list containing the values.

“Snapshot of the following statement, which uses the values method.”

005.eps Type the following statement, which uses the values() method and displays all the values in the dog5 dictionary, and then press Ent:

print(dog5.values())

Python displays dict_values(['Hondje', 'Boerboel', 24, 70]).

006.eps Type the following statement, which creates a variable named q and assigns to it the result of using the items() method on the dog5 dictionary. Press Ent.

q = dog5.items()

Note: The items() method returns a list of tuples, each containing a key/value pair.

“Snapshot of the following statement, which uses the print function.”

007.eps Type the following statement, which uses the print() function to display the contents of q. Press Ent.

print(q)

Python displays dict_items([('name', 'Hondje'), ('breed', 'Boerboel'), ('height', 24), ('weight', 70)]).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.61