Python / Core Python Fundamentals Interview Questions
How do Python dictionaries work and what are the most important operations?
A dictionary is Python's hash-map: an unordered (insertion-ordered since Python 3.7) collection of key-value pairs. Keys must be hashable (strings, numbers, tuples of hashable items); values can be anything. Lookup, insertion, and deletion are O(1) average-case.
user = {
'name': 'Alice',
'age': 30,
'active': True
}
# Access — raises KeyError if key missing
print(user['name']) # Alice
# Safe access — returns default if key missing
print(user.get('email', 'N/A')) # N/A
# Add / update
user['email'] = 'alice@example.com'
user.update({'age': 31, 'city': 'NYC'})
# Delete
del user['active']
role = user.pop('city', None) # removes and returns; default avoids KeyError
# Iterating
for key, value in user.items():
print(f'{key}: {value}')
# Keys and values as views
print(list(user.keys())) # ['name', 'age', 'email']
print(list(user.values())) # ['Alice', 31, 'alice@example.com']Dict comprehension builds dictionaries from iterables in one line:
squares = {x: x**2 for x in range(1, 6)} # {1:1, 2:4, 3:9, 4:16, 5:25}Checking membership tests keys only: 'name' in user is O(1). To check values you must iterate, which is O(n). For counting occurrences, collections.Counter is a dict subclass that auto-initialises missing keys to zero, making frequency analysis much cleaner.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
