Python Dictionaries - Interview Questions and Answers
A dictionary in Python is an unordered, mutable collection of key-value pairs. Each key is unique, and values can be of any data type. It is defined using curly braces {}
.
my_dict = {"key1": "value1", "key2": "value2"}
A dictionary is defined using curly braces {}
with key-value pairs separated by a colon :
.
my_dict = {"name": "Alice", "age": 25}
You can access a value using its corresponding key inside square brackets []
.
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
If you try to access a key that doesn't exist, a KeyError
is raised
my_dict = {"name": "Alice", "age": 25}
print(my_dict["gender"]) # KeyError: 'gender'
You can use the get()
method, which returns None
(or a default value) if the key does not exist.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.get("gender", "Not Found")) # Output: Not Found
You can add a new key-value pair by simply assigning a value to a new key.
my_dict = {"name": "Alice", "age": 25}
my_dict["gender"] = "Female"
You can update the value of an existing key by reassigning a new value to that key.
my_dict = {"name": "Alice", "age": 25}
my_dict["age"] = 26
You can use the del
keyword or the pop()
method to remove a key-value pair
my_dict = {"name": "Alice", "age": 25}
del my_dict["age"]
del
removes the key-value pair and does not return anything.pop()
removes the key-value pair and returns the value of the removed key.
my_dict = {"name": "Alice", "age": 25}
age = my_dict.pop("age") # Removes "age" and returns its value
The clear()
method removes all items from the dictionary.
my_dict = {"name": "Alice", "age": 25}
my_dict.clear() # Dictionary is now empty
You can use the in
keyword to check if a key exists in the dictionary
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # Output: True
You can use the keys()
method to get all the keys.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
You can use the values()
method to get all the values
my_dict = {"name": "Alice", "age": 25}
print(my_dict.values()) # Output: dict_values(['Alice', 25])
You can use the items()
method to get both keys and values.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25)])
You can iterate over the dictionary using a for loop. You can iterate over keys, values, or both.
my_dict = {"name": "Alice", "age": 25}
for key, value in my_dict.items():
print(key, value)
No, dictionary keys must be unique. If you assign a new value to an existing key, the previous value will be overwritten.
my_dict = {"name": "Alice", "age": 25}
my_dict["age"] = 26 # 'age' value is now 26
Dictionary keys must be immutable (e.g., strings, numbers, tuples). Lists and other mutable types cannot be used as keys.
You can merge dictionaries using the update()
method or the |
operator (Python 3.9+).
dict1 = {"name": "Alice"}
dict2 = {"age": 25}
dict1.update(dict2) # Merges dict2 into dict1
The setdefault()
method returns the value of a key if it exists; otherwise, it inserts the key with a specified default value.
my_dict = {"name": "Alice"}
print(my_dict.setdefault("age", 25)) # Output: 25
The fromkeys()
method creates a new dictionary from a sequence of keys, with each key having the same default value.
keys = ["name", "age"]
my_dict = dict.fromkeys(keys, "N/A")
You can copy a dictionary using the copy()
method.
original = {"name": "Alice", "age": 25}
new_dict = original.copy()
You can use the sorted()
function to sort the dictionary by keys.
my_dict = {"b": 2, "a": 1, "c": 3}
sorted_dict = sorted(my_dict.items()) # Sorts by keys
You can use the sorted()
function and pass a key
argument to sort by values
my_dict = {"a": 3, "b": 1, "c": 2}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1]) # Sorts by values
items()
returns a view of key-value pairs.keys()
returns a view of the keys.values()
returns a view of the values.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.items()) # [('name', 'Alice'), ('age', 25)]
The popitem()
method removes and returns the last key-value pair from the dictionary as a tuple.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.popitem()) # ('age', 25)
Nested dictionaries can be accessed using multiple keys
my_dict = {"person": {"name": "Alice", "age": 25}}
print(my_dict["person"]["name"]) # Output: Alice
No, dictionaries themselves are not sets, but their keys can be used to create a set.
You can check if a dictionary is empty by checking its length or using not
in a condition.
my_dict = {}
if not my_dict:
print("Dictionary is empty")
Dictionary comprehension allows you to create dictionaries using an expression inside curly braces.
my_dict = {x: x ** 2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
A dictionary can store keys and values of any data type, including lists, tuples, strings, and numbers.
Yes, you can reverse iterate over a dictionary using reversed()
or items()
with reversed()
.
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in reversed(my_dict.items()):
print(key, value)
You can merge multiple dictionaries using the update()
method or the **
unpacking operator (Python 3.5+).
dict1 = {"a": 1}
dict2 = {"b": 2}
dict3 = {"c": 3}
merged_dict = {**dict1, **dict2, **dict3}
You can use the len()
function to get the number of key-value pairs
my_dict = {"name": "Alice", "age": 25}
print(len(my_dict)) # Output: 2
You can use the dict()
constructor to convert a list of tuples into a dictionary
my_list = [("a", 1), ("b", 2)]
my_dict = dict(my_list)
Dictionaries provide fast lookups, allow efficient searching, and enable storing data in key-value pairs, making them ideal for situations where data retrieval speed is important.
Tutorials
Random Blogs
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Top 10 Blogs of Digital Marketing you Must Follow
- Top 10 Knowledge for Machine Learning & Data Science Students
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- String Operations in Python
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques