Graphics Reference
In-Depth Information
Dictionaries
Whereas lists are collections of items that are ordered and accessible by an integer index,
dictionaries
are col-
lections of items that are accessible via reference to other items. Dictionaries are represented by a comma-sep-
arated collection of pairs. The elements of the pairs are separated by colons, and the whole collection is within
curly brackets, as in this example:
{'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}
Each pair is called a
key-value pair
; the item to the left of the colon is the
key
, and the item to the right is
its corresponding
value
. A value in a dictionary can be accessed by using its key, just as an element of a list is
accessed by using its index:
>>> {'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}['mary']
29
A list of all the keys in a dictionary can be output by using the
keys()
method, as shown here:
>>> {'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}.keys()
['tom', 'john', 'mary', 'brit']
Operators
Operators
are the way a programming language determines the relationships between various data elements in
a program. You've already seen an important operator, the
=
operator, or
assignment operator
. The purpose of
this operator is to assign the value on the right of the operator to the variable on the left side of the operator. Be
careful: Although this looks like an equal sign, it is not the sign used to indicate that two terms have the same
value.
Python's
comparison operators
are shown in
Table 12-1
.
Table 12-1:
Python's Comparison Operators
Operator Value
Equal to
==
Greater than or equal to
>=
>
Greater than
Less than or equal to
<=
Less than
<
Not equal to
!=
You can see the difference between assignment and equality with this example:
>>> a=5
>>> a
5
>>> a==5
True
>>> a==6
False
Furthermore, logical terms can be put together using either the
and
or
or
keyword.