Python Dictionaries (Maps)

Python Dictionaries (Maps) Interview Questions

What is a dictionary (map) in Python?
A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and immutable (strings, numbers, tuples). Values can be of any type. Defined with curly braces {} or dict(). Example: {"name": "John", "age": 25, "city": "New York"}.
What are the key characteristics of Python dictionaries?
Dictionaries are unordered (Python 3.7+ preserves insertion order), mutable, use key-value pairs, keys must be hashable/immutable, values can be any type, provide O(1) average time complexity for lookups, and are implemented as hash tables.
How to access dictionary values?
1. Using square brackets: dict[key] (raises KeyError if key doesn't exist)
2. Using get() method: dict.get(key, default_value) (returns default if key doesn't exist)
3. Using setdefault(): dict.setdefault(key, default_value) (sets default if key doesn't exist)
What is dictionary comprehension in Python?
Dictionary comprehension creates dictionaries using concise syntax. Format: {key_expression: value_expression for item in iterable if condition}. Example: squares = {x: x**2 for x in range(5)} creates {0:0, 1:1, 2:4, 3:9, 4:16}.
What are the main dictionary methods?
keys() - returns view of keys
values() - returns view of values
items() - returns view of (key, value) pairs
get(key, default) - returns value or default
pop(key, default) - removes key and returns value
update(other_dict) - merges dictionaries
clear() - removes all items
What is the difference between dict[key] and dict.get(key)?
dict[key] raises a KeyError if the key doesn't exist. dict.get(key, default) returns the default value (None if not specified) if the key doesn't exist. Use get() when you're unsure if a key exists.
How to merge two dictionaries?
# Python 3.5+ using ** unpacking dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} merged = {**dict1, **dict2} # dict2 values override dict1 # Using update() method dict1.update(dict2) # modifies dict1 in-place # Python 3.9+ using | operator merged = dict1 | dict2 # dict2 values override dict1
What is the time complexity of dictionary operations?
get(), set(), delete: O(1) average
in operator: O(1) average
keys(), values(), items(): O(1) to create view
copy(): O(n)
Dictionaries use hash tables for O(1) average operations.
What is the setdefault() method?
setdefault(key, default_value) returns the value of key if it exists. If not, it inserts key with default_value and returns default_value. Useful for initializing dictionary entries. Example: dict.setdefault("count", 0) ensures "count" exists with value 0.
How to iterate through a dictionary?
my_dict = {"a": 1, "b": 2, "c": 3} # Iterate through keys for key in my_dict: print(key) # Iterate through key-value pairs for key, value in my_dict.items(): print(key, value) # Iterate through values for value in my_dict.values(): print(value) # Iterate through keys with index for i, key in enumerate(my_dict): print(i, key)
What is a dictionary view object?
dict.keys(), dict.values(), and dict.items() return view objects that provide dynamic views of dictionary entries. They reflect changes to the dictionary and support set-like operations for keys and items views.
How to create a dictionary from two lists?
keys = ["a", "b", "c"] values = [1, 2, 3] # Using zip() and dict() my_dict = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3} # Using dictionary comprehension my_dict = {keys[i]: values[i] for i in range(len(keys))}
What is defaultdict from collections module?
defaultdict is a dictionary subclass that provides default values for missing keys. You specify a default factory function. Example: from collections import defaultdict; d = defaultdict(list) creates dict where missing keys get empty list as value.
What is OrderedDict and when to use it?
OrderedDict from collections module maintains insertion order (now built-in dicts do too in Python 3.7+). Use OrderedDict when you need specific order behaviors like reordering (move_to_end()) or equality checking that considers order.
How to sort a dictionary by key or value?
my_dict = {"b": 2, "a": 1, "c": 3} # Sort by key sorted_by_key = dict(sorted(my_dict.items())) # {'a': 1, 'b': 2, 'c': 3} # Sort by value sorted_by_value = dict(sorted(my_dict.items(), key=lambda x: x[1])) # {'a': 1, 'b': 2, 'c': 3} # Sort by value descending sorted_desc = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))
What is dictionary unpacking?
Dictionary unpacking uses ** operator to unpack dictionary items. Example: func(**{"x": 1, "y": 2}) passes x=1, y=2 to function. Also used for merging: {**dict1, **dict2}. Python 3.9+ adds | operator for merging.
How to invert a dictionary (swap keys and values)?
original = {"a": 1, "b": 2, "c": 3} # Using dictionary comprehension (works if values are unique) inverted = {value: key for key, value in original.items()} # For non-unique values, group by value from collections import defaultdict inverted = defaultdict(list) for key, value in original.items(): inverted[value].append(key)
What are some practical use cases for dictionaries?
1. Storing configuration settings
2. Counting frequencies (histograms)
3. Caching/memoization
4. Implementing graphs (adjacency lists)
5. JSON-like data structures
6. Database record representations
7. Switch/case replacements
8. Grouping data by categories
What is the fromkeys() method?
dict.fromkeys(iterable, value=None) creates a new dictionary with keys from iterable and all values set to value. Example: dict.fromkeys(["a", "b", "c"], 0) creates {"a": 0, "b": 0, "c": 0}.
How to handle nested dictionaries?
# Creating nested dictionary nested = { "person1": {"name": "John", "age": 25}, "person2": {"name": "Jane", "age": 30} } # Accessing nested values name = nested["person1"]["name"] # "John" # Modifying nested values nested["person1"]["age"] = 26 # Using get() with nested age = nested.get("person1", {}).get("age") # Returns None if person1 doesn't exist # Using defaultdict for auto-nesting from collections import defaultdict nested = defaultdict(lambda: defaultdict(dict))
Note: Dictionaries are Python's implementation of hash tables/maps, providing O(1) average time complexity for lookups, insertions, and deletions. They're one of Python's most powerful and commonly used data structures. Dictionary comprehensions provide a concise way to create dictionaries. Remember that dictionary keys must be hashable (immutable), while values can be any Python object. In Python 3.7+, dictionaries preserve insertion order.
Python Dictionaries (Maps) Next