What is a dictionary in Python?

What is a dictionary in Python?

a) A collection of key-value pairs
b) A list with ordered elements
c) A set of unique, unordered elements
d) A tuple with immutable elements

Answer:

a) A collection of key-value pairs

Explanation:

A dictionary in Python is a collection of key-value pairs, where each key is unique and is used to access its corresponding value. Dictionaries are mutable, meaning that you can add, remove, or modify key-value pairs after the dictionary is created. Dictionaries are commonly used for mapping data and storing information that needs to be quickly retrieved using a key.

# Example of a dictionary
student = {"name": "John", "age": 20, "major": "Computer Science"}
print(student["name"])  # Output: John

# Adding a new key-value pair
student["grade"] = "A"
print(student)  # Output: {'name': 'John', 'age': 20, 'major': 'Computer Science', 'grade': 'A'}

In this example, the dictionary student contains keys like “name,” “age,” and “major,” each associated with a corresponding value. Dictionaries are ideal for storing and organizing data that is related by keys.

Dictionaries are one of the most powerful and flexible data structures in Python, allowing for efficient data retrieval and manipulation based on keys.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top