Concepts / Conditional Statements

Conditional Statements

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

  • 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.

In the real world

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.

contactskey-value pairsAliceemail addressBobemail addressCharlieemail addressDianaemail addresskeykeykeykey
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

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

Looking Up and Changing Entries

Worked example

Working with the contacts Dictionary

Use the contacts dictionary to understand the main dictionary operations.

  1. 1
    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.

  2. 2
    Add

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

  3. 3
    Modify

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

  4. 4
    Delete

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

Result

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

contactsexisting pairsnew key-value pairaddedexisting valueupdatedkey-value pairremovedassign a new keyassign an existing keyuse del
What changes inside a dictionary when a key-value pair is added, modified, or deleted?
Key point

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.
contactsbegin iterationAlicekey and emailBobkey and emailCharliekey and emailDianakey and emailCompleteall pairs processedfirst pairnext pairnext pairnext pairno pairs remain
How does control move through each key-value pair when retrieving all keys and values?

Mistakes with Dictionaries

  • Common mistake

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

    What it looks like

    Trying to retrieve a dictionary value by a numeric position instead of using its key

    Why it fails

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

    Do this instead

    Use the required key inside square brackets.

  • Common mistake

    Using a key that does not exist without checking

    What it looks like

    Accessing or deleting a key before testing whether it is present

    Why it fails

    The key may not exist in the dictionary.

    Do this instead

    Use the in operator to check key membership first.

  • Common mistake

    Assuming an assignment always adds a new entry

    What it looks like

    Assigning a value using a key that already exists

    Why it fails

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

    Do this instead

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

  • Common mistake

    Deleting only the value conceptually

    What it looks like

    Using del on a dictionary entry without recognizing what is removed

    Why it fails

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

    Do this instead

    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. 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.

Related concepts

More concepts starting with C