Dictionaries in Python

A dictionary in Python is a collection of key-value pairs. It is used to store data in an organized way, where each value is associated with a unique key.

Creating a Dictionary

In Python, a dictionary is a collection of key-value pairs. Each key is connected to a value, and you can use the key to access the corresponding value.

To create a dictionary:

  • Use curly braces {}.
  • Separate each key and value with a colon :.
  • Use a comma , to separate different key-value pairs.

Example:

        
# Creating a dictionary of fruits and their colors
fruits = {
    "Apple": "Red",
    "Banana": "Yellow",
    "Cherry": "Red",
    "Mango": "Orange"
}
print(fruits)
        
    

Explanation:

  • The dictionary fruits has fruit names as keys ("Apple", "Banana", etc.) and their colors as values ("Red", "Yellow", etc.).
  • You can store any type of information as a value, including numbers, strings, lists, or even another dictionary.

Output:

        
{'Apple': 'Red', 'Banana': 'Yellow', 'Cherry': 'Red', 'Mango': 'Orange'}
        
    

Accessing Values in a Dictionary

You can retrieve a value from a dictionary by using its key inside square brackets [ ].

Example:

        
# Dictionary of fruits and their colors
fruits = {
    "Apple": "Red",
    "Banana": "Yellow",
    "Cherry": "Red"
}

# Access the color of "Banana"
print(fruits["Banana"])  # Output: Yellow
        
    

Explanation:

  • fruits["Banana"] looks for the key "Banana" in the dictionary and returns its value, which is "Yellow".
  • If the key doesn’t exist in the dictionary, Python will raise a KeyError.
  • Keys must be unique in a dictionary, but values can repeat.

Output:

        
Yellow
        
    

Additional Notes:

  • Dictionaries are very fast for accessing values because they use a special structure called a hash table.
  • You can also use the get() method to access values without causing an error if the key doesn’t exist. For example: fruits.get("Grapes", "Not Found") will return "Not Found".

Adding and Updating Entries in a Dictionary

In Python, you can easily add a new key-value pair to a dictionary, or update the value of an existing key:

1. Adding a New Key-Value Pair

To add a new entry, just assign a value to a new key. If the key doesn't already exist in the dictionary, it will be added:

        
# Creating a dictionary
fruits = {"Apple": "Red", "Banana": "Yellow"}

# Adding a new pair for "Cherry"
fruits["Cherry"] = "Red"

print(fruits)
        
    

Explanation:

  • Here, fruits["Cherry"] = "Red" adds a new key "Cherry" with the value "Red" to the dictionary.
  • If "Cherry" was already a key in the dictionary, this would update its value.

Output:

        
{"Apple": "Red", "Banana": "Yellow", "Cherry": "Red"}
        
    

2. Updating an Existing Key-Value Pair

If you want to change the value associated with an existing key, you can simply reassign a new value to that key:

        
# Updating the value of "Banana"
fruits["Banana"] = "Green"

print(fruits)
        
    

Explanation:

  • Here, fruits["Banana"] = "Green" updates the value of the key "Banana" to "Green".
  • If the key does not exist, it will be treated as adding a new key-value pair.

Output:

        
{"Apple": "Red", "Banana": "Green", "Cherry": "Red"}
        
    

Removing Entries from a Dictionary

You can remove a key-value pair from a dictionary using the del statement:

1. Using del to Remove a Key-Value Pair

The del statement removes the entire key-value pair from the dictionary:

        
# Removing the key "Apple"
fruits = {"Apple": "Red", "Banana": "Yellow", "Cherry": "Red"}
del fruits["Apple"]

print(fruits)
        
    

Explanation:

  • Here, del fruits["Apple"] removes the key "Apple" and its associated value from the dictionary.
  • If the key doesn’t exist, Python will raise a KeyError.

Output:

        
{"Banana": "Yellow", "Cherry": "Red"}
        
    

Practice Challenge

Try creating a dictionary that stores the names and ages of three people. Then:

  • Add a new person's age to the dictionary.
  • Update the age of one person.
  • Remove one person from the dictionary.

Here's a starting point:

        
people = {
    "Alice": 25,
    "Bob": 30,
    "Charlie": 35
}
people["David"] = 40  # Adding a new person
people["Alice"] = 26  # Updating Alice's age
del people["Bob"]  # Removing Bob
print(people)