12. Dictionaries in Python

Quiz: 0/6

Dictionaries are a way to store and organize related pieces of data in Python. They are useful when you need to quickly look up a value based on a specific key, just like looking up a word in a dictionary to find its meaning.

Each item in a dictionary is a key-value pair, where the key is a unique identifier, and the value is the data associated with that key.

Creating Dictionaries

To create a dictionary, you use curly braces {} and separate each key-value pair with a colon :. Here’s how to create a simple dictionary:

my_dict = {"name": "Alice", "age": 25, "city": "Paris"}

In this example:

  • "name", "age", and "city" are the keys.
  • "Alice", 25, and "Paris" are the values associated with those keys.

Accessing, adding, updating, and removing key-value pairs

Accessing a value:

To get a value, you use the key inside square brackets []:

print(my_dict["name"])  # Output: Alice

Adding a new key-value pair:

You can add new pairs to the dictionary by assigning a value to a new key:

my_dict["job"] = "Engineer"  # Adds a new key "job" with the value "Engineer"

Updating a value:

You can change the value of an existing key:

my_dict["age"] = 26  # Updates the value of "age" to 26

Removing a key-value pair:

You can remove a pair using the del keyword:

del my_dict["city"]  # Removes the key "city" and its associated value

Iterating over keys, values, and items

You can loop through a dictionary to access its keys, values, or both:

Keys:

for key in my_dict:
    print(key)

This will print each key in the dictionary.

Values:

for value in my_dict.values():
    print(value)

This will print each value in the dictionary.

Key-value pairs:

for key, value in my_dict.items():
    print(f"{key}: {value}")

This will print each key along with its associated value.

Nested Dictionaries

A nested dictionary is a dictionary where the value of a key is another dictionary. This is useful when you want to organize data more hierarchically.

my_dict = {
    "person": {"name": "Bob", "age": 30},
    "city": "New York"
}

In this example, the value for the "person" key is another dictionary containing "name" and "age". You can access data inside nested dictionaries like this:

print(my_dict["person"]["name"])  # Output: Bob

Summary

  • Dictionaries are used to store key-value pairs, making it easy to look up data using a key.
  • You can create, access, update, and remove key-value pairs.
  • You can iterate over the keys, values, or both.
  • Nested dictionaries allow you to store more complex, hierarchical data.

Dictionaries are a powerful way to organize and manage data in Python!

Hands-On Practise

Exercise: Managing a student's profile

Step-by-step Instructions:

  1. Create the Dictionary:
    Create a dictionary called student_profile to store the following information:

    • name: The student's name (string).
    • age: The student's age (integer).
    • major: The student's major (string).
  2. Add a New Key-Value Pair:
    Add a key hometown with a value of your choice (string) to the student_profile.

  3. Update the Age:
    Update the student's age to a new value (e.g., increase by 1).

  4. Remove the Hometown:
    Remove the hometown key from the dictionary.

  5. Display the Profile:
    Use a loop to print the student's profile by iterating through the dictionary. Display both the key and the value for each entry.

Challenge:

Try extending this exercise by adding more details to the student's profile, such as:

  • email: The student's email address.
  • courses: A list of courses the student is taking.

Then, iterate through the updated dictionary and display all the information.

Output:

Quizzes: 0/6

Question 1:

What is a dictionary in Python?

  • A collection of ordered key-value pairs.
  • A collection of unordered key-value pairs.
  • A collection of values without keys.
  • A type of list that can store both keys and values.

Question 2:

Which method is used to add a new key-value pair to a dictionary in Python?

  • append()
  • add()
  • insert()
  • assignment (using `=`)

Question 3:

What is the correct way to access a value in a dictionary by its key?

  • dictionary.get(key)
  • dictionary[key]
  • Both of the above
  • dictionary.retrieve(key)

Question 4:

How can you remove a key-value pair from a dictionary in Python?

  • Using the `remove()` method.
  • Using the `del` keyword.
  • Using the `pop()` method.
  • All of the above.

Question 5:

What is the correct syntax to iterate over both keys and values in a dictionary?

  • for key, value in dictionary.items():
  • for key in dictionary.keys():
  • for value in dictionary.values():
  • for item in dictionary:

Question 6:

What is a nested dictionary in Python?

  • A dictionary where the value is another dictionary.
  • A dictionary where the key is another dictionary.
  • A dictionary with only integer keys.
  • A dictionary that contains lists as values.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonTuples in PythonNext lessonSets in Python