Concepts / Conditional Statements

Conditional Statements

A dictionary is a data structure that stores key-value pairs, allowing you to look up values by their meaningful keys rather than by numeric position.

  • Programming

From Position to Meaning

A dictionary is a data structure that stores key-value pairs. Instead of finding a value by a numeric position, you find it by using a meaningful key. This makes a dictionary useful when the identifier for a piece of information is more useful than its position.

A contacts dictionary can connect each person's name to that person's email address. The name is the key, and the email address is the value. To find a person's email address, you use the person's name rather than a numeric position.

keykeykeykeycontactskey-value pairsAliceemail addressBobemail addressCharlieemail addressDianaemail address
How does a dictionary connect a meaningful key to its value instead of retrieving an item by numeric position?

Creating Key-Value Pairs

Dictionaries are created with curly braces. Inside the braces, each key is followed by a colon and its corresponding value. Multiple key-value pairs are separated by commas. The general structure is {key1: value1, key2: value2}. Keys must be unique and immutable.

Dictionary partPurpose
Curly bracesEnclose the dictionary
KeyProvides the meaningful identifier
ColonSeparates a key from its value
ValueStores the information associated with the key
CommaSeparates one pair from the next

The parts of dictionary syntax

containscontainscontainsDictionarycurly braceskey: valuefirst pairkey: valuenext pairkey: valuenext pair
How does dictionary syntax organize several keys and their corresponding values into one data structure?

Looking Up and Changing Entries

Working with the contacts Dictionary

Use the contacts dictionary to understand the main dictionary operations.

Access: Use dictionary_name[key] to retrieve the value associated with a key. For the contacts dictionary, placing a person's name inside square brackets retrieves that person's email address.

Add: Use dictionary_name[new_key] = new_value to add a new key-value pair.

Modify: Use dictionary_name[existing_key] = new_value to update the value associated with an existing key.

Delete: Use del dictionary_name[key] to permanently remove both the selected key and its associated value.

A dictionary is mutable: after it is created, entries can be added, modified, or deleted.

assign a new keyassign an existing keyuse delcontactsexisting pairsnew key-value pairaddedexisting valueupdatedkey-value pairremoved
What changes inside a dictionary when a key-value pair is added, modified, or deleted?

The len() function returns the number of keys in a dictionary, which is also the number of key-value pairs.

Processing Every Pair

When you need to process every key-value pair, use the .items() method with a for loop. The pattern for key, value in dictionary.items(): provides both parts of each pair during each iteration. The pair is unpacked into the variables named key and value.

  • Use for key, value in dictionary.items(): when both keys and values are needed.
  • Use for key in dictionary: when only keys are needed.
  • Use for value in dictionary.values(): when only values are needed.
first pairnext pairnext pairnext pairno pairs remaincontactsbegin iterationAlicekey and emailBobkey and emailCharliekey and emailDianakey and emailCompleteall pairs processed
How does control move through each key-value pair when retrieving all keys and values?

Mistakes with Dictionaries

  • Treating a dictionary as if its values were found by numeric position

    A dictionary is designed for lookup by meaningful keys rather than numeric position.

    Fix: Use the required key inside square brackets.

  • Using a key that does not exist without checking

    The key may not exist in the dictionary.

    Fix: Use the in operator to check key membership first.

  • Assuming an assignment always adds a new entry

    Assigning to an existing key updates its value rather than creating another entry with the same key.

    Fix: Decide whether the operation is intended to add a new key or modify an existing value.

  • Deleting only the value conceptually

    The del operation removes both the selected key and its associated value.

    Fix: Use del dictionary_name[key] when the entire key-value pair should be removed.

Practice and Review

MEDIUM

A contacts dictionary stores names as keys and email addresses as values. Describe which dictionary operation you would use to retrieve one person's email address, add a new contact, update an existing email address, remove a contact, check whether a contact exists, and process every contact.

Hints
  • Retrieval uses a key inside square brackets.
  • Adding and modifying both use assignment with a key.
  • Deletion uses del.
  • Membership checking uses in.
  • Processing both parts of every pair uses .items().
  1. A dictionary organizes information as key-value pairs. Curly braces create the structure, keys identify values, and keys must be unique and immutable. Square-bracket lookup retrieves a value, assignment adds or updates an entry, and del removes an entry. The in operator checks whether a key exists. The .items() method supports iteration through both keys and values, while dictionary iteration can also process only keys or only values.

Key Takeaways

  • Dictionaries store key-value pairs and retrieve values by meaningful keys rather than numeric position.
  • Dictionary syntax uses curly braces, colons between keys and values, and commas between pairs.
  • Dictionaries are mutable: entries can be accessed, added, modified, and deleted.
  • The in operator checks key existence, and len() counts key-value pairs.
  • The .items(), dictionary, and .values() iteration patterns retrieve pairs, keys, or values.