left-icon

Python Succinctly®
by Jason Cannon

Previous
Chapter

of
A
A
A

CHAPTER 6

Dictionaries

Dictionaries


Another data type in Python is a dictionary. A dictionary holds key-value pairs, which are referred to as items. You will hear dictionaries referred to in different ways including: associative arrays, hashes, or hash tables.

Dictionaries are generated using comma separated items surrounded by curly braces. The item begins with a key, followed by a colon, and concluded with a value. The pattern is dictionary_name = {key_1: value_1, key_N: value_N}. In order to create an empty dictionary, use dictionary_name = {}.

Any items in a dictionary can be retrieved by key. To do so, enclose the key within brackets immediately following the dictionary name. The pattern is dictionary_name[key].

Code Listing 188

contacts = {'David': '555-0123', 'Tom': '555-5678'}

davids_phone = contacts['David']

toms_phone = contacts['Tom']

print('Dial {} to call David.'.format(davids_phone))

print('Dial {} to call Tom.'.format(toms_phone))

Output:

Code Listing 189

Dial 555-0123 to call David.

Dial 555-5678 to call Tom.

Not only are you able to access values by key, you can also set values by key. The pattern is dictionary_name[key] = value.

contacts = {'David': '555-0123', 'Tom': '555-5678'}

contacts['David'] = '555-0000'

davids_phone = contacts['David']

print('Dial {} to call David.'.format(davids_phone))

Output:

Code Listing 190

Dial 555-0000 to call David.

Adding Items to a Dictionary

Keep in mind that you can easily add new items to a dictionary through the process of assignment. The pattern for this is dictionary_name[new_key] = value. In order to determine the number of items in a dictionary, first use the len() built-in function and pass in a dictionary.

Code Listing 191

contacts = {'David': '555-0123', 'Tom': '555-5678'}

contacts['Nora'] = '555-2413'

print(contacts)

print(len(contacts))

Output:

Code Listing 192

{'Nora': '555-2413', 'Tom': '555-5678', 'David': '555-0123'}

3

Removing Items from a Dictionary

To remove an item from a dictionary, use the del statement. The pattern is del dictionary_name[key].

Code Listing 193

contacts = {'David': '555-0123', 'Tom': '555-5678'}

del contacts['David']

print(contacts)

Output:

Code Listing 194

{'Tom': '555-5678'}

Keep in mind that the values within a dictionary do not have to be of the same data type. In the following example you’ll see that while the value for the David key is a list, the value for the Tom key is a string.

Code Listing 195

contacts = {

    'David': ['555-0123', '555-0000'],

    'Tom': '555-5678'

}

print('David:')

print(contacts['David'])

print('Tom:')

print(contacts['Tom'])

Output:

Code Listing 196

David:

['555-0123', '555-0000']

Tom:

555-5678

When you are assigning the items to the contacts dictionary you can use additional spaces as it will greatly improve readability

As a result of the fact dictionary_name('key_name') is capable of storing its associated value, you can act upon it like you would the actual values. To illustrate this, let's use a for loop for all of David's phone numbers.

Code Listing 197

contacts = {

    'David': ['555-0123', '555-0000'],

    'Tom': '555-5678'

}

for number in contacts['David']:

    print('Phone: {}'.format(number))

Output:

Code Listing 198

Phone: 555-0123

Phone: 555-0000

Finding a Key in a Dictionary

If you would like to find out whether a certain key exists within a dictionary, use the value in dictionary_name.keys() syntax. If the value is in fact a key in the dictionary, True will be returned. If it is not, then False will be returned.

Code Listing 199

contacts = {

    'David': ['555-0123', '555-0000'],

    'Tom': '555-5678'

}

if 'David' in contacts.keys():

    print("David's phone number is:")

    print(contacts['David'][0])

if 'Nora' in contacts.keys():

    print("Nora's phone number is:")

    print(contacts['Nora'][0])

Output:

Code Listing 200

David's phone number is:

555-0123

Take note that 'David' in contacts evaluates to True, so the code block which follows the if statement will be executed. Since 'Nora' in contacts evaluates to False, the code block which follows that statement will not execute. Also, since contacts['David'] holds a list, you can act on it as a list. Accordingly, contacts['David'][0] will return the first value in the list.

Finding a Value in a Dictionary

Using the values() dictionary method returns a list of values within the dictionary. Use the value in list syntax to determine if the value actually exists within the list. If the value is in the list, True will be returned. Otherwise False will be returned.

Code Listing 201

contacts = {

    'David': ['555-0123', '555-0000'],

    'Tom': '555-5678'

}

print ('555-5678' in contacts.values())

Output:

Code Listing 202

True

Looping through a Dictionary

If you are looking to loop through items in a dictionary, one pattern you can use is for key_variable in dictionary_name:. The code block that follows after the for statement will then be executed for every item listed in the dictionary. To access the value of the item in the for loop, use the dictionary_name[key_variable] pattern. Unlike lists, dictionaries are unordered. The for loop will ensure that all of the items in the dictionary will be processed; however, there is absolutely no guarantee that they will be processed in the order you desire.

It is a common practice to name dictionaries by using a plural noun, such as in the case of contacts. The standard pattern of the for loop will use the singular form of the dictionary name as the key variable. For example, for contact in contacts or for person in people.

Code Listing 203

contacts = {

    'David': '555-0123',

    'Tom': '555-5678'

}

for contact in contacts:

    print('The number for {0} is {1}.'.format(contact, contacts[contact]))

Output:

Code Listing 204

The number for Tom is 555-5678.

The number for David is 555-0123.

You may also opt to utilize two variables when defining a for loop in order to process items within a dictionary. While the first variable comprises the key, the second one will contain the value. The pattern is for key_variable, value_variable in dictionary_name.items():.

Code Listing 205

contacts = {'David': '555-0123', 'Tom': '555-5678'}

for person, phone_number in contacts.items():

    print('The number for {0} is {1}.'.format(person, phone_number))

Output:

Code Listing 206

The number for Tom is 555-5678.

The number for David is 555-0123.

Nesting Dictionaries

Since the values contained in a dictionary can be of any data type you have the ability to nest dictionaries. In the following example, names are the keys for the contacts dictionary, while phone and email are the keys used within the nested dictionary. Each individual in this contact list has both a phone number and an email address. If you want to know David's email address you can retrieve that information using contacts['David']['email'].

Make sure to pay close attention to the location of colons, quotation marks, commas, and braces. Try using additional white space when you are coding these types of data structures to help visually represent the data structure.

Code Listing 207

contacts = {

    'David': {

        'phone': '555-0123',

        'email': '[email protected]'

    },

    'Tom': {

        'phone': '555-5678',

        'email': '[email protected]'

    }

}

for contact in contacts:

    print("{}'s contact info:".format(contact))

    print(contacts[contact]['phone'])

    print(contacts[contact]['email'])

Output:

Code Listing 208

Tom's contact info:

555-5678

[email protected]

David's contact info:

555-0123

[email protected]

Review

Dictionaries hold key-value pairs, known as items. dictionary_name = {key_1: value_1, key_N: value_N}

A key allows you to access the values stored in a dictionary. dictionary_name[key]

Assignments allow you to add or change values in a dictionary. dictionary_name[key] = value

The del statement removes items from a dictionary. del dictionary_name[key]

To determine if a key exists within a dictionary, use the value in dictionary_name syntax, which will return a Boolean.

The values() dictionary method will return a list of the values that are stored in that dictionary.

Loop through a dictionary using the for key_variable in dictionary_name: syntax.

Dictionary values can be made up of any data type, including other dictionaries.

Exercises

Interesting Facts

Try to create a dictionary that has a listing of people and includes one interesting fact about each of them. Display each person and their interesting fact on the screen. From there, alter a fact about one of the people on the list. Also, add an extra person and corresponding fact to the list. Display the newly created list of people and facts. Try running the program multiple times and take note of whether the order changes.

Sample output:

Code Listing 209

Jeff: Was born in France.

David: Was a mascot in college.

Anna: Has arachnophobia.

Dylan: Has a pet hedgehog.

Jeff: Was born in France.

David: Can juggle.

Anna: Has arachnophobia.

Solution

Code Listing 210

def display_facts(facts):

    """Displays facts"""

    for fact in facts:

        print('{}: {}'.format(fact, facts[fact]))

    print()

facts = {

    'David': 'Was a mascot in college.',

    'Jeff':  'Was born in France.',

    'Anna': 'Has arachnophobia.'

}

display_facts(facts)

facts['David'] = 'Can juggle.'

facts['Dylan'] = 'Has a pet hedgehog.'

display_facts(facts)

Resources

Data Structures (Dictionaries): https://docs.python.org/3/tutorial/datastructures.html

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.