Interview Questions, Answers and Tutorials

Adding, updating, and deleting key-value pairs

Adding, updating, and deleting key-value pairs

Welcome to our interactive course on Python dictionaries! In this session, we will explore how to work with Python dictionaries, specifically focusing on adding, updating, and deleting key-value pairs. Dictionaries are like real-life dictionaries but for programming. They help us store and organize data in a structured way.

Prerequisites:

Before diving into this course, you should have a basic understanding of Python programming concepts such as variables, data types, and basic syntax.

Course Outline:

  1. Understanding Python Dictionaries
  2. Adding Key-Value Pairs
  3. Updating Key-Value Pairs
  4. Deleting Key-Value Pairs
  5. Practice Questions

1. Understanding Python Dictionaries:

Python dictionaries are a data structure that stores key-value pairs. Think of them like a phone book where you look up a name (key) to find a phone number (value). Dictionaries are enclosed in curly braces {}, and each key-value pair is separated by a colon :.

Example:

my_dict = {'apple': 5, 'banana': 3, 'orange': 8}

2. Adding Key-Value Pairs:

To add a new key-value pair to a dictionary, simply assign a value to a new key.

Example:

my_dict['grape'] = 10

3. Updating Key-Value Pairs:

If the key already exists in the dictionary, you can update its value by reassigning it.

Example:

my_dict['apple'] = 7

4. Deleting Key-Value Pairs:

To remove a key-value pair from a dictionary, you can use the del keyword or the pop() method.

Example:

del my_dict['banana']

or

my_dict.pop('orange')

5. Practice Questions:

  1. Question: Add a new key-value pair to the following dictionary:

student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90}

Solution:

student_scores['David'] = 78

  1. Question: Update Bob’s score to 80 in the student_scores dictionary.

Solution:

student_scores['Bob'] = 80

  1. Question: Delete Charlie’s score from the student_scores dictionary.

Solution:

del student_scores['Charlie']

Congratulations! You’ve now mastered adding, updating, and deleting key-value pairs in Python dictionaries. Keep practicing to solidify your understanding, and soon you’ll be a Python dictionary pro!