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

(singke) #1

In Listing 9.1, a dictionary called student is created. Then the type function is used on it. You
can see that student is a dictionary (dict) type.


LISTING 9.1 Creating an Empty Dictionary


>>> student = {}
>>> type (student)
<class 'dict'>
>>>

Populating a Dictionary


Populating a dictionary means putting keys and their associated values into the dictionary. To
populate a dictionary, you use this syntax:


Click here to view code image


dictionary_name = {key1:value1, key2:value2...}

By the Way: No Need to Pre-Create
You don’t have to create an empty dictionary before you start to populate it. You can
create it and populate it all with one command. Just issue the command to populate the
dictionary, and Python automatically creates the dictionary for you.

Listing 9.2 shows an example of populating a dictionary. Here the student dictionary is populated
with three students. The key is the student ID number, such as 400A42, and the value is the student’s
name.


LISTING 9.2 Populating a Dictionary


Click here to view code image


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

Notice in Listing 9.2 that the three student key/value elements are between a pair of curly brackets.
Each key/value element is set apart from the other elements by a comma. Also, both the key and the
value are character strings and thus must have quotation marks around them.


By the Way: No Order in a Dictionary
The elements in a Python dictionary are not ordered. This is why you may put into a
dictionary key/value pairs in a certain order, and then they end up being displayed in a
different order! You can see this in Listing 9.2.

You can also add key/value pairs to a dictionary one at a time. The syntax for this method is

Free download pdf