dictionary Class in Python
dictionary Class in Python
🔹 Understanding the dict Class in Python
The dict class in Python represents a dictionary, which is a key-value mapping. Each
key in the dictionary is unique, and it maps to a specific value.
1️⃣ What is a Dictionary?
A dictionary stores data in the format { key: value } .
🔹 Example of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
✅ Key Properties of a Dictionary:
Each key must be unique.
Values can be any data type (string, integer, list, another dictionary, etc.).
Order is preserved in Python 3.7+ (before that, it was unordered).
📌 Note: {} creates an empty dictionary, not a set.
2️⃣ Accessing Dictionary Elements
🔹 Method 1: Using []
print(thisdict["model"]) # Output: Mustang
🔹 Method 2: Using .get()
print(thisdict.get("model")) # Output: Mustang
✅ Difference?
[] will throw an error if the key does not exist.
.get() will return None if the key does not exist.
3️⃣ Getting Dictionary Keys & Values
🔹 Getting All Keys
print(thisdict.keys())
# Output: dict_keys(['brand', 'model', 'year'])
🔹 Getting All Values
print(thisdict.values())
# Output: dict_values(['Ford', 'Mustang', 1964])
🔹 Getting All Key-Value Pairs
print(thisdict.items())
# Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
✅ .items() returns a list of tuples, where each tuple is a (key, value) pair.
4️⃣ Adding & Modifying Dictionary Elements
🔹 Adding a New Key-Value Pair
thisdict["color"] = "white"
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'white'}
🔹 Modifying an Existing Key
thisdict["year"] = 2020
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color':
'white'}
🔹 Using .update() to Modify Multiple Keys
thisdict.update({"year": 2022, "color": "red"})
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2022, 'color':
'red'}
5️⃣ Creating a Dictionary Using dict()
You can use the dict() constructor to create a dictionary.
thisdict = dict(name="John", age=36, country="Norway")
print(thisdict)
# Output: {'name': 'John', 'age': 36, 'country': 'Norway'}
📌 Note:
In dict() , keys must be strings.
It is an alternative to the {} dictionary syntax.
6️⃣ Handling Duplicate Keys
🔹 If you define duplicate keys, the last value will override the previous ones.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020 # Overrides previous "year" value
}
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
7️⃣ Checking for Key Existence
🔹 Use the in keyword to check if a key exists.
if "model" in thisdict:
print("Yes, 'model' is one of the keys in thisdict")
8️⃣ Removing Elements from a Dictionary
🔹 Removing a Specific Key ( pop() )
thisdict.pop("model")
print(thisdict)
# Output: {'brand': 'Ford', 'year': 2020, 'color': 'red'}
✅ If the key does not exist, pop() raises an error.
🔹 Removing the Last Inserted Item ( popitem() )
thisdict.popitem()
print(thisdict)
✅ Removes the last inserted key-value pair (since Python 3.7+ maintains order).
✅ The .popitem() method removes and returns the last inserted key-value pair in
dictionaries from Python 3.7 onwards.
🔹 Removing a Key Using del
del thisdict["year"]
print(thisdict)
# Output: {'brand': 'Ford', 'color': 'red'}
✅ If the key does not exist, del raises an error.
🔹 Deleting the Entire Dictionary
del thisdict
print(thisdict) # This will cause an error because the dictionary no longer
exists.
🔹 Clearing the Dictionary ( clear() )
thisdict.clear()
print(thisdict) # Output: {}
✅ The dictionary remains, but all items are removed.
MCQ
1️⃣ What is the correct syntax to create an empty
dictionary?
A) dict = []
B) dict = {}
C) dict = ()
D) dict = set()
2️⃣ What will be the output of the following code?
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["model"])
A) Ford
B) Mustang
C) 1964
D) Error
3️⃣ What happens if you try to access a key that does
not exist using [] ?
A) Returns None
B) Prints an empty string
C) Raises a KeyError
D) Creates a new key automatically
4️⃣ What will be the output of the following code?
thisdict = {"name": "Alice", "age": 25}
print(thisdict.get("gender"))
A) None
B) KeyError
C) "gender"
D) 0
5️⃣ Which of the following is NOT a valid dictionary
key?
A) 42
B) "name"
C) (1, 2, 3)
D) ["list_key"]
6️⃣ What is the output of the following code?
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020}
print(thisdict)
A) {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'year': 2020}
B) {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
C) Error
D) None
7️⃣ Which method is used to get all keys of a
dictionary?
A) .values()
B) .keys()
C) .items()
D) .get_keys()
8️⃣ Which method removes the last inserted key-value
pair?
A) .pop()
B) .remove()
C) .del()
D) .popitem()
9️⃣ What will be the output of the following code?
thisdict = {"name": "John", "age": 30}
thisdict.update({"age": 35, "city": "New York"})
print(thisdict)
A) {'name': 'John', 'age': 30, 'city': 'New York'}
B) {'name': 'John', 'age': 35, 'city': 'New York'}
C) {'name': 'John', 'age': 30}
D) Error
🔟 What does the clear() method do?
A) Deletes the dictionary
B) Removes all key-value pairs
C) Returns all keys
D) Removes the last key
1️⃣1️⃣ What will be the output of the following code?
thisdict = {"a": 1, "b": 2}
del thisdict
print(thisdict)
A) {}
B) None
C) Error
D) {'a': 1, 'b': 2}
1️⃣2️⃣ What is the correct way to check if a key exists
in a dictionary?
A) "key" exists in dict
B) dict.has_key("key")
C) "key" in dict
D) dict.contains("key")