0% found this document useful (0 votes)
20 views1 page

Python Crash Course, 3rd Edition2-031

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views1 page

Python Crash Course, 3rd Edition2-031

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

We start by defining the same dictionary that we’ve been working with.

We then print this dictionary, displaying a snapshot of its information.


Next, we add a new key-value pair to the dictionary: the key 'x_position'
and the value 0. We do the same for the key 'y_position'. When we print the
modified dictionary, we see the two additional key-value pairs:

{'color': 'green', 'points': 5}


{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

The final version of the dictionary contains four key-value pairs. The
original two specify color and point value, and two more specify the alien’s
position.
Dictionaries retain the order in which they were defined. When you
print a dictionary or loop through its elements, you will see the elements in
the same order they were added to the dictionary.

Starting with an Empty Dictionary


It’s sometimes convenient, or even necessary, to start with an empty diction-
ary and then add each new item to it. To start filling an empty dictionary,
define a dictionary with an empty set of braces and then add each key-value
pair on its own line. For example, here’s how to build the alien_0 dictionary
using this approach:

[Link] alien_0 = {}

alien_0['color'] = 'green'
alien_0['points'] = 5

print(alien_0)

We first define an empty alien_0 dictionary, and then add color and
point values to it. The result is the dictionary we’ve been using in previous
examples:

{'color': 'green', 'points': 5}

Typically, you’ll use empty dictionaries when storing user-supplied data


in a dictionary or when writing code that generates a large number of key-
value pairs automatically.

Modifying Values in a Dictionary


To modify a value in a dictionary, give the name of the dictionary with the
key in square brackets and then the new value you want associated with
that key. For example, consider an alien that changes from green to yellow
as a game progresses:

[Link] alien_0 = {'color': 'green'}


print(f"The alien is {alien_0['color']}.")

94 Chapter 6

You might also like