Python Dictionary

Python Dictionary Interview Questions

What is a dictionary in Python?
A dictionary is an unordered, mutable collection of key-value pairs. Dictionaries are defined using curly braces {} with key:value pairs separated by commas. Example: my_dict = {"name": "John", "age": 25, "city": "New York"}.
What are the characteristics of dictionary keys?
Dictionary keys must be unique and immutable (strings, numbers, tuples with immutable elements). Keys cannot be mutable objects like lists or dictionaries. Values can be of any data type and can be duplicated.
How to access dictionary values?
You can access values using square brackets with the key: my_dict["name"]. Use get() method to avoid KeyError: my_dict.get("name") returns None if key doesn't exist, or my_dict.get("name", "default") for a default value.
How to add or modify items in a dictionary?
Add or modify using assignment: my_dict["key"] = value. If key exists, value is updated; if not, new key-value pair is added. Use update() method to merge dictionaries: my_dict.update({"new_key": "new_value"}).
How to remove items from a dictionary?
1. del my_dict["key"] - removes specific key. 2. pop("key") - removes and returns value. 3. popitem() - removes and returns last inserted item (Python 3.7+). 4. clear() - removes all items.
What are dictionary views?
Dictionary views are dynamic objects that reflect dictionary changes. Three view methods: keys() - returns view of all keys, values() - returns view of all values, items() - returns view of all key-value pairs as tuples.
What is dictionary comprehension?
Dictionary comprehension creates dictionaries using a concise syntax: {key: value for item in iterable}. Example: squares = {x: x*x for x in range(5)} creates {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}.
How to check if a key exists in a dictionary?
Use the in operator: if "key" in my_dict:. You can also use if "key" in my_dict.keys(): but the first method is more efficient as it uses hash table lookup.
What is the difference between dict.get() and dict[key]?
dict[key] raises KeyError if key doesn't exist. dict.get(key) returns None if key doesn't exist, and dict.get(key, default) returns specified default value. Use get() when you're unsure if key exists.
How to iterate through a dictionary?
Multiple ways: 1. for key in my_dict: - iterates keys. 2. for value in my_dict.values(): - iterates values. 3. for key, value in my_dict.items(): - iterates key-value pairs. 4. Use enumerate() for index.
What is the default dictionary (collections.defaultdict)?
defaultdict from collections module automatically creates default values for missing keys. Example: from collections import defaultdict; d = defaultdict(list) - creates empty list for missing keys.
What is OrderedDict?
OrderedDict from collections module maintains insertion order (Python 3.7+ regular dicts also maintain order). OrderedDict has additional methods: move_to_end() and popitem(last=True/False).
How to merge two dictionaries?
Multiple ways: 1. dict1.update(dict2) - modifies dict1. 2. {**dict1, **dict2} - creates new dict (Python 3.5+). 3. dict1 | dict2 - union operator (Python 3.9+). 4. Dictionary comprehension.
What is dictionary unpacking?
Dictionary unpacking uses ** operator to unpack dictionary into another dictionary or function arguments. Example: new_dict = {**dict1, **dict2} or function(**kwargs) to pass dictionary as keyword arguments.
How to sort a dictionary?
Dictionaries are unordered (pre-3.7) but can be sorted: 1. By keys: sorted_dict = dict(sorted(my_dict.items())). 2. By values: sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1])). Returns new dict.
What is the time complexity of dictionary operations?
Average case O(1): get, set, delete, check membership. Worst case O(n) due to hash collisions. Dictionary operations are highly optimized and typically very fast due to hash table implementation.
How to create a dictionary from two lists?
Use zip() function: keys = ["a", "b", "c"]; values = [1, 2, 3]; my_dict = dict(zip(keys, values)) creates {"a": 1, "b": 2, "c": 3}. Use dictionary comprehension for more control.
What are nested dictionaries?
Dictionaries containing other dictionaries as values. Example: nested = {"person1": {"name": "John", "age": 25}, "person2": {"name": "Jane", "age": 30}}. Access with multiple keys: nested["person1"]["name"].
How to copy a dictionary?
1. Shallow copy: copy_dict = my_dict.copy() or dict(my_dict). 2. Deep copy (for nested dicts): import copy; deep_copy = copy.deepcopy(my_dict). Assignment (=) creates reference, not copy.
What are common use cases for dictionaries?
1. JSON data handling. 2. Configuration storage. 3. Counting frequency (using defaultdict). 4. Caching/memoization. 5. Grouping data. 6. Switch-case replacement. 7. Object representation. 8. Fast lookups by key.
dict[key] vs get(key) when missing?
Bracket raises KeyError; get returns default—choose based on control flow.
dict.fromkeys(keys, []) trap?
Same list shared—use list comprehension or factory loop per key.
collections.defaultdict(list) pattern?
Auto-appends buckets—avoid manual key existence checks.
ChainMap lookup order?
Searches dicts left-to-right—first match wins for reads.
{**a, **b} collision?
Right-hand mapping wins same keys—explicit merge semantics.
Python 3.9 d1 | d2?
New merged dict—operands unchanged unlike update.
keys() live view?
Reflects mutations—snapshot if you need stability via list(d.keys()).
Shallow copy nested dict?
copy() duplicates outer shell—inner dicts shared—use deepcopy.
popitem() order 3.7+?
LIFO on last inserted—stack-like eviction.
setdefault race in threading?
Not magically atomic for compound ops—still need locks for shared mutation.
Tuple key vs list?
Tuple hashable—list not—why composite keys use tuples.
None as key?
Allowed—hashes like other singletons.
sorted(d) sorts what?
Keys only—wrap items() for value sorts via key=.
Duplicate keys in literal?
Last wins silently—bug source in large literals.
== on dicts ignores order?
Since Python 3.7 order preserved but equality still pairwise keys/values only.
collections.Counter subtract?
Can produce zero/negative counts—filter when presenting histograms.
__missing__ on dict subclass?
Hook for custom defaulting—powers patterns beyond defaultdict.
JSON keys type?
Always strings after parse—may differ from Python tuple keys mindset.
dict(zip(keys, vals)) length mismatch?
zip truncates—silent data loss if lengths differ.
del d[k] vs pop?
pop returns value; del statement cannot capture.
WeakKeyDictionary why?
Avoid circular refs holding keys alive—caching patterns.
items() in Python 3?
View objects dynamic—iterating while mutating needs care.
copy() vs dict() constructor?
Both shallow—pick readability; constructor accepts iterable of pairs too.
Hashable key requirement depth?
Key’s __hash__ and equality must be consistent—mutable violates.
collections.OrderedDict still useful?
Move-to-end and equality semantics differ—legacy APIs may rely on it.
Dict comprehension overwrite same key?
Later iteration wins—mirrors literal duplicate behavior.
get nested safely?
d.get("a", {}).get("b")—or explicit checks to avoid AttributeError on None.
| requires both mappings?
Both operands dict-like for |—PEP 584.
clear() id?
Same dict object emptied—references still valid.
dict.fromkeys single default scalar?
Reused object—fine for immutables, deadly for lists.
Why not use dict as hash key?
Unhashable type—use frozenset of items or tuple pairs if frozen snapshot.
Note: Dictionaries are one of Python's most powerful and frequently used data structures. Their hash table implementation provides O(1) average time complexity for lookups, making them ideal for fast data retrieval. Understanding dictionary operations, methods, and advanced features is crucial for writing efficient Python code.
Prev: Sets Python Dictionary Next: Maps