Dictionaries & Sets
Dictionaries are everywhere in data work — JSON responses from APIs, column renaming maps, value replacement maps. Know them thoroughly.
How do you create a dictionary and access values?
person = {"name": "Rahul", "age": 28, "city": "Noida"}
person["name"] # "Rahul"
person.get("salary") # None (no KeyError)
person.get("salary", 0) # 0 (default value)Always use .get() when the key might not exist — it returns None instead of raising a KeyError. Essential when parsing API responses or JSON files where keys are optional.
How do you add, update, and delete keys in a dictionary?
d = {"a": 1, "b": 2}
d["c"] = 3 # add new key
d["a"] = 10 # update existing key
del d["b"] # delete key
d.pop("c") # delete and return valuepop() is safer than del — it can accept a default value if the key does not exist: d.pop("x", None). Use this pattern when cleaning optional fields.
How do you iterate over a dictionary?
d = {"a": 1, "b": 2, "c": 3}
for key in d: # iterates over keys
print(key)
for k, v in d.items(): # iterates over key-value pairs
print(k, v)
list(d.keys()) # ["a", "b", "c"]
list(d.values()) # [1, 2, 3].items() is the most common pattern — you need both key and value. In Pandas, dict iteration is used for column renaming: df.rename(columns={"old": "new"}).
What is a set and when do you use it over a list?
cities = {"Delhi", "Mumbai", "Noida", "Delhi"} # duplicates removed
print(cities) # {"Delhi", "Mumbai", "Noida"}
# Set operations:
a = {1, 2, 3}
b = {2, 3, 4}
a & b # intersection: {2, 3}
a | b # union: {1, 2, 3, 4}
a - b # difference: {1}Sets automatically remove duplicates and support fast membership testing (O(1)). Use when you need unique values or to find common/different elements between two groups.
How do you merge two dictionaries?
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
# Python 3.9+
merged = d1 | d2
# All Python 3:
merged = {**d1, **d2}
# update() — modifies d1 in place:
d1.update(d2)The ** unpacking syntax is common in interviews. In data work, you merge config dicts, combine column rename maps, or merge API parameter dicts before making requests.
EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS
Want to master Python with live practice?
Join our Python for Data Analysis course — live classes in Noida and online across India.
Book Free Demo Class →