• Discover
  • Collections
  • Board
  • Create
  • Profile
  • Settings
Paths

Lesson 5.3: Dictionaries: Key-Value Pairs

Lesson 5.3: Dictionaries: Key-Value Pairs

4 min read

Dictionaries are Python's built-in mapping type.

They store data in `key:

valuepairs, where each key is unique and maps to a specific value. Dictionaries are unordered (in Python versions before 3.7, ordered in 3.7+ by insertion), mutable, and optimized for retrieving values when the key is known. They are defined by enclosing elements in curly braces{}`.

Creating Dictionaries

python
# An empty dictionary empty_dict = {} # A dictionary of programming languages and their years of creation programming_languages = { "Python": 1991, "Java": 1995, "C++": 1985, "JavaScript": 1995 } # A dictionary with mixed key/value types mixed_dict = { "name": "Alice", "age": 30, "is_student": True, 1: "one" } print(empty_dict) print(programming_languages) print(mixed_dict) print(type(programming_languages)) # Output: <class 'dict'>

Key Rules:

  • Keys must be unique: If you assign a new value to an existing key, the old value is overwritten.
  • Keys must be immutable: Keys can be strings, numbers, or tuples. Lists and other mutable types cannot be used as keys.
  • Values can be of any data type and can be duplicates.

Accessing Dictionary Values

You access values by referencing their corresponding key using square brackets [] or the get() method.

**1.

Using [] (Square Brackets):

**

python
print(programming_languages["Python"]) # Output: 1991 # print(programming_languages["Ruby"]) # This would raise a KeyError if 'Ruby' doesn't exist

2. Using dict.get(key, default_value): The get() method is safer as it returns None (or a specified default_value) if the key is not found, instead of raising an error.

python
print(programming_languages.get("Java")) # Output: 1995 print(programming_languages.get("Ruby")) # Output: None print(programming_languages.get("Ruby", 2000)) # Output: 2000 (default value if key not found)

Modifying Dictionaries

Dictionaries are mutable, allowing you to add, change, or remove key-value pairs.

**1.

Adding new key-value pairs:

**

python
programming_languages["Go"] = 2009 print(programming_languages) # Output: {'Python': 1991, 'Java': 1995, 'C++': 1985, 'JavaScript': 1995, 'Go': 2009}

**2.

Modifying an existing value:

**

python
programming_languages["Java"] = 1996 # Update Java's year print(programming_languages) # Output: {'Python': 1991, 'Java': 1996, ...}

**3.

Removing key-value pairs:

**

  • del dict[key]: Removes the item with the specified key.
  • dict.pop(key, default_value): Removes the item with the specified key and returns its value. Can provide a default if key not found.
  • dict.clear(): Removes all items from the dictionary.
python
del programming_languages["C++"] print(programming_languages) # Output: {'Python': 1991, 'Java': 1996, 'JavaScript': 1995, 'Go': 2009} popped_value = programming_languages.pop("Go") print(f"Popped value: {popped_value}, Dict now: {programming_languages}") # Output: Popped value: 2009, Dict now: {'Python': 1991, 'Java': 1996, 'JavaScript': 1995} programming_languages.clear() print(programming_languages) # Output: {}

Iterating Through Dictionaries

Dictionaries can be iterated in several ways:

  • Looping through keys (default):
    python
    person = {"name": "Jane Doe", "age": 28, "city": "London"} for key in person: print(key) # Output: name, age, city
  • dict.keys(): Returns a view object of all keys.
    python
    for key in person.keys(): print(key)
  • dict.values(): Returns a view object of all values.
    python
    for value in person.values(): print(value) # Output: Jane Doe, 28, London
  • dict.items(): Returns a view object of all key-value pairs as tuples.
    python
    for key, value in person.items(): print(f"{key}: {value}") # Output: # name: Jane Doe # age: 28 # city: London

Dictionaries are essential for representing structured data, such as records or configurations, where you need to associate unique identifiers (keys) with specific pieces of information (values).

Key Takeaways:

  • Dictionaries store data as key: value pairs, defined with {}.
  • Keys must be unique and immutable; values can be any type.
  • Access values using dict[key] (raises KeyError if not found) or dict.get(key, default) (safer).
  • Modify by assigning to an existing key, add by assigning to a new key.
  • Remove items with del dict[key], dict.pop(key), or dict.clear().
  • Iterate over keys (default), keys(), values(), or items() for key-value pairs.
End of lesson
👏Well done!
Previous Lesson
Lesson 5.2: Tuples: Immutability and Use Cases
Next Lesson
Lesson 5.4: Sets: Unique Elements and Set Operations

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 5.1: Lists: Creation, Accessing, Modifying

Lesson 5.2: Tuples: Immutability and Use Cases

Lesson 5.3: Dictionaries: Key-Value Pairs

Lesson 5.4: Sets: Unique Elements and Set Operations

Quiz

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 5.1: Lists: Creation, Accessing, Modifying

Lesson 5.2: Tuples: Immutability and Use Cases

Lesson 5.3: Dictionaries: Key-Value Pairs

Lesson 5.4: Sets: Unique Elements and Set Operations

Quiz