Chapter 4- Python Dictionaries
Q1: What is a dictionary in Python?
Ans. A Python dictionary is similar to a regular word dictionary. It is
a powerful tool that lets you store, organize, and access data using
keys and values.
In this analogy:
Keys are like words,
Values are like their meanings.
Each key in a Python dictionary is unique and maps to a specific
value.
Example:
student = {"name": "Alice", "age": 20, "grade": "A"}
Q2: What are the characteristics of dictionaries?
Ans.
Unordered
Mutable (can be changed)
Keys are unique
Defined using {} curly braces
Dictionary values can repeat.
Q3: How is a dictionary different from a list or tuple?
Ans.
List/Tuple: Ordered collection accessed by index.
Dictionary: Unordered collection accessed by key.
Q4: How do you access values in a dictionary?
Ans. person = {"name": "Bob", "age": 25}
print(person["name"]) # Output: Bob
Q5: What happens if you access a key that does not exist?
Ans: It raises a KeyError.
Q6: What is a nested dictionary?
Ans: A nested dictionary is a dictionary that contains another
dictionary as the value of a key. In short, it is a dictionary inside
another dictionary.
Example:
age = {
‘A’: {‘john’:10, ‘Alice’:30},
‘B’: {‘peter’:30, ‘Max’: 35}
}
Q7: How do you delete a key-value pair from a dictionary?
Ans.
To delete a key-value pair from a dictionary in Python, you can
use the del keyword.
Example:
student = {"name": "Amit", "age": 13, "class": 8}
del student["age"] # This will remove the "age" key and its value
print(student)
Output:
{'name': 'Amit', 'class': 8}
You can also use the pop() method:
[Link]("class")
print(student)
Output:
{'name': 'Amit'}
Q8: What is the update() method in dictionaries?
Ans: It adds or updates key-value pairs from another dictionary.
Example- a = {"x": 1}
b = {"y": 2}
[Link](b)
print(a) # {'x': 1, 'y': 2}
Example- Subject={“Math”:”Monday”,”Science”:”Tuesday”}
[Link]({“Computer”:”Friday”})
print(Subject)
Output-
Subject={“Math”:”Monday”,”Science”:”Tuesday”,Computer”:”Friday “}
Q8: Define the following functions:
1) keys(): keys() function is used to check all the keys in the dictionary.
Example:
Subject={“Math”:”Monday”,”Science”:”Tuesday”}
print([Link]())
Output: The output will print all the keys in the dictionary
dict_keys([“Math”,”Science”])
2) values(): values() function is used to check all the values in the dictionary.
Example:
Subject={“Math”:”Monday”,”Science”:”Tuesday”}
print([Link]())
Output: The output will print all the values in the dictionary
dict_values([“Monday”,”Tuesday”])
3) items(): items() function is used to check both the keys and values in the
dictionary.
Example:
Subject={“Math”:”Monday”,”Science”:”Tuesday”}
print([Link]())
Output: The output will print all the items in the dictionary
dict_items([(“Math”,“Monday”),(“Science”,”Tuesday”)])