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.
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.
Python Dictionary Next