Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

10.6 Chapter summary

Highlights from this chapter include:

At this point, you should be able to use dictionaries in your programs. The programming practice below ties together most topics presented in the chapter.

Table 10.10 Chapter 10 reference.
ConceptDescription
Dictionary creation using curly braces my_dict = {key1:value1, key2:value2}
Dictionary creation using the dict() method # Using a list my_list = [(key1, value1), (key2, value2)] my_dict = dict(my_list) # Using keyword arguments my_dict = dict(key1=value1, key2=value2) # From another dictionary old_dict = {key1: value1, key2: value2} new_dict = dict(old_dict)
Accessing dictionary items my_dict = {key1: value1, key2: value2} # Accessing item using square bracket notation my_dict[key1] # Accessing item through get() method my_dict.get(key1)
Accessing all dictionary items my_dict.items()
Accessing all dictionary keys my_dict.keys()
Accessing all dictionary values my_dict.values()
Adding a new key-value pair or updating an existing key-value pair my_dict = {key1: value1, key2: value2} # Updating an item using square bracket notation my_dict[key1] = new_value # Adding a new key-value pair using square bracket notation my_dict[key3] = value3 # Updating an item using update() method my_dict.update({key1: new_value}) # Adding a new key-value pair using update() method my_dict.update({key3: value3})
Deleting a key-value pair from a dictionary my_dict = {key1: value1, key2: value2} # Using del keyword del my_dict[key1] # Using pop() method deleted_value = my_dict.pop(key1)
Iterating over a dictionary for key in dictionary: # Loop expression   # Statements to execute in the loop #Statements to execute after the loop
Nested dictionaries { key_1:{key11:value11, key12:value12}, key_2:{key21:value21, key22:value22} }
Dictionary comprehension {key_expression: value_expression for element in iterable}

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.