0% found this document useful (0 votes)
1 views10 pages

Python Dictionary Interview Questions

python dictionary

Uploaded by

Vishal Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views10 pages

Python Dictionary Interview Questions

python dictionary

Uploaded by

Vishal Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Dictionaries - Interview Questions,

Tips and Practice Problems


A focused guide for Python dictionary interview preparation.

A compact interview reference with practical questions, shortcuts, common patterns, and easy-to-hard coding
problems.

1. Common Python Dictionary Interview Questions


Basic questions
1. What is a Python dictionary?

A dictionary stores key-value pairs. It is useful when you want fast lookup by key.

person = {"name": "Vishal", "age": 50}


print(person["name"]) # Vishal

2. Are dictionary keys unique?

Yes. If you insert the same key again, the old value is replaced.

d = {"a": 1, "a": 2}
print(d) # {'a': 2}

3. What types can be dictionary keys?

Keys must be hashable. Common keys include strings, numbers, and tuples of immutable values.

d = {}
d["name"] = "Python"
d[10] = "ten"
d[(1, 2)] = "point"

Lists cannot be keys because they are mutable.

# d[[1, 2]] = "bad" # TypeError

4. How do you add or update values?

scores = {}
scores["Asha"] = 90
scores["Ravi"] = 85
scores["Asha"] = 95

print(scores) # {'Asha': 95, 'Ravi': 85}

5. What is the difference between d[key] and [Link](key)?

d[key] raises KeyError if the key is missing. get() returns None or a default value.

d = {"a": 1}

print([Link]("b")) # None

Python Dictionaries - Interview Questions and Practice Problems Page 1


print([Link]("b", 0)) # 0
# print(d["b"]) # KeyError

6. How do you delete a key?

d = {"a": 1, "b": 2}

value = [Link]("a")
print(value) # 1
print(d) # {'b': 2}

Using del:

d = {"a": 1, "b": 2}
del d["a"]

7. How do you loop through a dictionary?

d = {"a": 1, "b": 2}

for key in d:
print(key, d[key])

for key, value in [Link]():


print(key, value)

8. What do keys(), values(), and items() return?

d = {"a": 1, "b": 2}

print([Link]()) # dict_keys(['a', 'b'])


print([Link]()) # dict_values([1, 2])
print([Link]()) # dict_items([('a', 1), ('b', 2)])

9. How do you check if a key exists?

d = {"a": 1}

if "a" in d:
print("key exists")

10. What is a dictionary comprehension?

squares = {n: n * n for n in range(1, 5)}


print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}

2. Useful Dictionary Tips


Count frequency of list elements
nums = [1, 2, 2, 3, 3, 3]
freq = {}

for n in nums:
freq[n] = [Link](n, 0) + 1

print(freq) # {1: 1, 2: 2, 3: 3}

Count frequency of characters


s = "banana"
freq = {}

for ch in s:
freq[ch] = [Link](ch, 0) + 1

print(freq) # {'b': 1, 'a': 3, 'n': 2}

Python Dictionaries - Interview Questions and Practice Problems Page 2


Group items by a key
words = ["cat", "car", "dog", "door"]
groups = {}

for word in words:


first = word[0]
[Link](first, []).append(word)

print(groups) # {'c': ['cat', 'car'], 'd': ['dog', 'door']}

Use defaultdict for easier grouping


from collections import defaultdict

words = ["cat", "car", "dog", "door"]


groups = defaultdict(list)

for word in words:


groups[word[0]].append(word)

print(dict(groups))

Use Counter for counting


from collections import Counter

nums = [1, 2, 2, 3, 3, 3]
freq = Counter(nums)

print(freq)
print(freq.most_common(2))

Merge dictionaries
a = {"x": 1, "y": 2}
b = {"y": 20, "z": 3}

merged = {**a, **b}


print(merged) # {'x': 1, 'y': 20, 'z': 3}

Modern syntax:

merged = a | b

Invert a dictionary
d = {"a": 1, "b": 2}
inverted = {value: key for key, value in [Link]()}

print(inverted) # {1: 'a', 2: 'b'}

Be careful: if values are duplicated, later keys overwrite earlier keys.

Sort a dictionary by key


d = {"b": 2, "a": 1, "c": 3}

for key, value in sorted([Link]()):


print(key, value)

Sort a dictionary by value


d = {"a": 3, "b": 1, "c": 2}

items = sorted([Link](), key=lambda item: item[1])


print(items) # [('b', 1), ('c', 2), ('a', 3)]

Python Dictionaries - Interview Questions and Practice Problems Page 3


Get the key with maximum value
scores = {"Asha": 90, "Ravi": 85, "Mina": 95}

best = max(scores, key=[Link])


print(best) # Mina

Safe nested dictionary access


data = {"user": {"name": "Vishal"}}
name = [Link]("user", {}).get("name")
print(name)

3. Important Dictionary Patterns for Interviews


Frequency map pattern
Use this when the problem asks for counts, duplicates, most frequent values, anagrams, or first non-repeating items.

def frequency(nums):
freq = {}

for n in nums:
freq[n] = [Link](n, 0) + 1

return freq

Fast lookup pattern


Use a dictionary when you need to remember something and look it up quickly later.

def two_sum(nums, target):


seen = {}

for i, n in enumerate(nums):
need = target - n

if need in seen:
return [seen[need], i]

seen[n] = i

return []

Grouping pattern
Use a dictionary where each key maps to a list.

def group_by_length(words):
groups = {}

for word in words:


length = len(word)
[Link](length, []).append(word)

return groups

Prefix sum pattern


Use a dictionary to remember how many times a running sum has appeared.

def subarray_sum(nums, k):


prefix_counts = {0: 1}
current_sum = 0
count = 0

Python Dictionaries - Interview Questions and Practice Problems Page 4


for n in nums:
current_sum += n
need = current_sum - k
count += prefix_counts.get(need, 0)
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1

return count

Memoization pattern
Use a dictionary to store results of expensive function calls.

def fib(n, memo=None):


if memo is None:
memo = {}

if n in memo:
return memo[n]

if n <= 1:
return n

memo[n] = fib(n - 1, memo) + fib(n - 2, memo)


return memo[n]

4. Easy Dictionary Problems


Problem 1: Count frequency of each element
def frequency(nums):
freq = {}

for n in nums:
freq[n] = [Link](n, 0) + 1

return freq

print(frequency([1, 2, 2, 3, 3, 3]))

Problem 2: Count words in a sentence


def word_count(sentence):
counts = {}

for word in [Link]():


counts[word] = [Link](word, 0) + 1

return counts

print(word_count("to be or not to be"))

Problem 3: First non-repeating character


def first_non_repeating(s):
freq = {}

for ch in s:
freq[ch] = [Link](ch, 0) + 1

for ch in s:
if freq[ch] == 1:
return ch

return None

Problem 4: Merge two dictionaries by adding values


def merge_add(a, b):
result = [Link]()

Python Dictionaries - Interview Questions and Practice Problems Page 5


for key, value in [Link]():
result[key] = [Link](key, 0) + value

return result

print(merge_add({"a": 1, "b": 2}, {"b": 3, "c": 4}))

Problem 5: Invert a dictionary


def invert(d):
result = {}

for key, value in [Link]():


result[value] = key

return result

print(invert({"a": 1, "b": 2}))

Problem 6: Find most frequent element


def most_frequent(nums):
freq = {}

for n in nums:
freq[n] = [Link](n, 0) + 1

return max(freq, key=[Link])

print(most_frequent([1, 2, 2, 3, 3, 3])) # 3

5. Medium Dictionary Problems


Problem 7: Two sum
def two_sum(nums, target):
seen = {}

for i, n in enumerate(nums):
need = target - n

if need in seen:
return [seen[need], i]

seen[n] = i

return []

print(two_sum([2, 7, 11, 15], 9)) # [0, 1]

Problem 8: Group anagrams


def group_anagrams(words):
groups = {}

for word in words:


key = "".join(sorted(word))
[Link](key, []).append(word)

return list([Link]())

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

Problem 9: Top k frequent elements


def top_k_frequent(nums, k):
freq = {}

for n in nums:
freq[n] = [Link](n, 0) + 1

Python Dictionaries - Interview Questions and Practice Problems Page 6


items = sorted([Link](), key=lambda item: item[1], reverse=True)
return [key for key, count in items[:k]]

print(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]

Problem 10: Subarray sum equals k


def subarray_sum(nums, k):
prefix_counts = {0: 1}
current_sum = 0
count = 0

for n in nums:
current_sum += n
need = current_sum - k
count += prefix_counts.get(need, 0)
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1

return count

print(subarray_sum([1, 1, 1], 2)) # 2

Problem 11: Longest substring without repeating characters


def longest_unique_substring(s):
last_seen = {}
left = 0
best = 0

for right, ch in enumerate(s):


if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1

last_seen[ch] = right
best = max(best, right - left + 1)

return best

print(longest_unique_substring("abcabcbb")) # 3

Problem 12: Find all duplicates


def find_duplicates(nums):
freq = {}
result = []

for n in nums:
freq[n] = [Link](n, 0) + 1
if freq[n] == 2:
[Link](n)

return result

print(find_duplicates([1, 2, 3, 2, 4, 3])) # [2, 3]

6. Harder Dictionary Problems


Problem 13: LRU cache using OrderedDict
from collections import OrderedDict

class LRUCache:
def __init__(self, capacity):
[Link] = capacity
[Link] = OrderedDict()

def get(self, key):


if key not in [Link]:
return -1

[Link].move_to_end(key)
return [Link][key]

Python Dictionaries - Interview Questions and Practice Problems Page 7


def put(self, key, value):
if key in [Link]:
[Link].move_to_end(key)

[Link][key] = value

if len([Link]) > [Link]:


[Link](last=False)

Problem 14: Longest consecutive sequence


Use a set for membership and a dictionary only if you also want to store extra information such as lengths or counts.

def longest_consecutive(nums):
num_set = set(nums)
longest = 0

for n in num_set:
if n - 1 not in num_set:
current = n
length = 1

while current + 1 in num_set:


current += 1
length += 1

longest = max(longest, length)

return longest

Problem 15: Design a simple hash map wrapper


This is not a replacement for Python's real dict. It is a toy interview exercise.

class MyHashMap:
def __init__(self):
[Link] = 1009
[Link] = [[] for _ in range([Link])]

def _index(self, key):


return hash(key) % [Link]

def put(self, key, value):


bucket = [Link][self._index(key)]

for i, pair in enumerate(bucket):


if pair[0] == key:
bucket[i] = (key, value)
return

[Link]((key, value))

def get(self, key):


bucket = [Link][self._index(key)]

for k, value in bucket:


if k == key:
return value

return None

def remove(self, key):


bucket = [Link][self._index(key)]

for i, pair in enumerate(bucket):


if pair[0] == key:
[Link](i)
return

Problem 16: Build an adjacency list for a graph


def build_graph(edges):
graph = {}

Python Dictionaries - Interview Questions and Practice Problems Page 8


for a, b in edges:
[Link](a, []).append(b)
[Link](b, []).append(a)

return graph

edges = [("A", "B"), ("A", "C"), ("B", "D")]


print(build_graph(edges))

7. Interview Tips for Dictionaries


- Use dictionaries when you need fast lookup by key.
- Use get() when a key may be missing.
- Use setdefault() or defaultdict(list) for grouping.
- Use Counter for clean frequency counting.
- Remember that dictionary keys must be hashable.
- Be careful when inverting a dictionary with duplicate values.
- For most coding interview problems, a dictionary is used to trade extra space for faster time.

Common complexities:

- d[key], d[key] = value, and key in d are O(1) average case.


- Iterating over all keys/items is O(n).
- Sorting dictionary items is O(n log n).
- A dictionary uses extra memory to provide fast lookup.

8. Good Practice Problem List


Easy
- Count frequency of numbers.
- Count words in a sentence.
- Find first non-repeating character.
- Merge two dictionaries.
- Invert a dictionary.
- Find most frequent value.
- Check whether two strings are anagrams.

Medium
- Two sum.
- Group anagrams.
- Top k frequent elements.
- Subarray sum equals k.
- Longest substring without repeating characters.
- Find all duplicates.
- Build a phone-book style lookup.

Python Dictionaries - Interview Questions and Practice Problems Page 9


Difficult
- LRU cache.
- Design a hash map.
- Word ladder helper maps.
- Alien dictionary graph.
- Minimum window substring.
- Prefix-sum problems with negative numbers.
- Graph adjacency-list problems.

Python Dictionaries - Interview Questions and Practice Problems Page 10

You might also like