Python Dictionary Inbuilt Functions with Edge Cases
🔧 What is a Dictionary in Python?
A dictionary is a collection of key-value pairs, where each key is unique.
example = {'name': 'Alice', 'age': 25, 'city': 'New York'}
✅ 1. get(key, default=None)
Returns value for the key if it exists; otherwise returns default.
d = {'name': 'Manoj', 'age': 25}
print(d.get('name')) # Output: 'Manoj'
print(d.get('gender', 'N/A')) # Output: 'N/A'
Edge Cases:
print(d.get('class')) # Output: None
✅ 2. keys()
Returns a view object of dictionary keys.
d = {'a': 1, 'b': 2}
print(list(d.keys())) # Output: ['a', 'b']
✅ 3. values()
Returns a view object of dictionary values.
d = {'a': 1, 'b': 2}
print(list(d.values())) # Output: [1, 2]
✅ 4. items()
Returns a view object of (key, value) tuples.
d = {'a': 1, 'b': 2}
for k, v in d.items():
print(k, v)
# Output: a 1
b2
✅ 5. update([other])
Updates and adds news key to the dictionary with key-value pairs from
another dictionary or iterable.
d.update({'c': 3})
print(d) # Output: {'a': 1, 'b': 2, 'c': 3}
d.update([(‘a’,7) , ('d', 4), ('e', 5)]) # Output: {'a': 7, 'b': 2, 'c': 3, ‘d’: 4, ‘e’: 5}
✅ 6. pop(key, default)
Removes specified key and returns its value.
print(d.pop('a')) # Output: 7
Edge Case:
print(d.pop('z', 'Not Found')) # Output: 'Not Found'
# print(d.pop('z')) --> KeyError if no default is provided
✅ 7. popitem()
Removes and returns the last inserted item. Applicable for dictionaries
after version 3.7
print(d.popitem()) # Example: ('e', 5)
Edge Case:
empty = {}
# empty.popitem() --> KeyError
✅ 8. clear()
Removes all items from the dictionary.
d.clear()
print(d) # Output: {}
Edge Case:
d.clear() # Safe even if already empty
✅ 9. copy()
Returns a shallow copy. If values are mutable (like lists), changes in the
copy will affect the original.
original = {'x': [1, 2]}
shallow = original.copy()
shallow['x'].append(3)
print(original) # Output: {'x': [1, 2, 3]}
✅ 10. fromkeys(keys, value=None)
Creates a new dictionary from keys and a common value. If value is
mutable (like a list), all keys share the same object.
keys = ['a', 'b']
new_d = dict.fromkeys(keys, 0)
print(new_d) # Output: {'a': 0, 'b': 0}
Edge Case:
new_d = dict.fromkeys(['x', 'y'], [])
new_d['x'].append(1)
print(new_d) # Output: {'x': [1], 'y': [1]}
✅ 11. zip(keys, values)
Zip(keys, values) pairs up items from both lists. dict(zip(...)) converts
those pairs into key-value pairs.
keys = ['a', 'b']
values = [1, 2, 3]
print(dict(zip(keys, values))) #Output: {'a’: 1, ‘b’: 2}