Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

dictionary_name[key1] = value1, as shown in Listing 9.3.


LISTING 9.3 Populating a Dictionary One Pair at a Time


Click here to view code image


>>> student['000B35'] = 'Raz Pi'
>>> student
{'300A04': 'Jason Jones', '000B35': 'Raz Pi', '400A42': 'Paul Bohall'}
>>>

There are a couple important items to note about key/value pairs:


The key cannot be a list.
The key must be an immutable object.
The key can be a string.
The key can be a number (integer or floating point).
The key can be a tuple.
The key must belong to only one value (no duplicate keys allowed).

The rules concerning the value in a key/value pair are much more simple. Basically, a value can be
anything.


Obtaining Data from a Dictionary


Once a dictionary is populated, you can obtain and use the elements from it. To obtain a single
dictionary value, you use this syntax:


dictionary_name[key]

Obviously, with this method, you need to know the key in order to obtain its associated value.


In Listing 9.4, a data value was obtained from the sample student dictionary. By using the associated
value’s key, the value was obtained.


LISTING 9.4 Obtaining a Dictionary Value via Its Key


>>> student['000B35']
'Raz Pi'
>>>

By the Way: Mappings
Key/value pairs are sometimes called mappings. This is because a single key maps
directly to a particular value.

You need to know a few rules about looking up key/value pair elements:


If you enter a dictionary lookup with a key that doesn’t exist, you get a KeyError exception.
When using a character string for a key, you must use the correct case.
Free download pdf