30 Essential Python Dictionary Tricks Every Developer Should Know
This tutorial walks through thirty practical Python dictionary operations—from creating and accessing entries to merging, comprehensions, sorting, and deletion—providing clear code examples and expected outputs to help readers master this versatile data structure.
1. Create a dictionary
# Create dictionary
my_dict = {"name": "Zhang San", "age": 25, "city": "Beijing"}
print(my_dict)Output: {'name': 'Zhang San', 'age': 25, 'city': 'Beijing'}
2. Access a value
# Access a value
print(my_dict["name"])Output: Zhang San
3. Modify a value
# Modify a value
my_dict["age"] = 26
print(my_dict)Output: {'name': 'Zhang San', 'age': 26, 'city': 'Beijing'}
4. Add a key‑value pair
# Add a key‑value pair
my_dict["job"] = "Programmer"
print(my_dict)Output: {'name': 'Zhang San', 'age': 26, 'city': 'Beijing', 'job': 'Programmer'}
5. Delete a key‑value pair
# Delete a key‑value pair
del my_dict["city"]
print(my_dict)Output: {'name': 'Zhang San', 'age': 26, 'job': 'Programmer'}
6. Get dictionary length
# Get dictionary length
print(len(my_dict))Output: 3
7. Get all keys
# Get all keys
print(my_dict.keys())Output: dict_keys(['name', 'age', 'job'])
8. Get all values
# Get all values
print(my_dict.values())Output: dict_values(['Zhang San', 26, 'Programmer'])
9. Get all items
# Get all items
print(my_dict.items())Output: dict_items([('name', 'Zhang San'), ('age', 26), ('job', 'Programmer')])
10. Iterate over items
# Iterate over items
for key, value in my_dict.items():
print(key, value)Output:
name Zhang San
age 26
job Programmer
11. Merge two dictionaries
# Merge two dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
12. Convert two lists to a dictionary
# Convert two lists to a dictionary
keys = ["name", "age", "city"]
values = ["Zhang San", 25, "Beijing"]
list_to_dict = dict(zip(keys, values))
print(list_to_dict)Output: {'name': 'Zhang San', 'age': 25, 'city': 'Beijing'}
13. Dictionary comprehension – create
# Create a dictionary with comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
14. Dictionary comprehension – filter
# Filter items where value > 25
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
filtered = {k: v for k, v in my_dict.items() if v > 25}
print(filtered)Output: {'a': 100, 'c': 300}
15. Dictionary comprehension – transform values
# Double each value
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
updated = {k: v*2 for k, v in my_dict.items()}
print(updated)Output: {'a': 200, 'b': 50, 'c': 600, 'd': 20}
16. Dictionary comprehension – transform keys and values
# Upper‑case keys and double values
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
transformed = {k.upper(): v*2 for k, v in my_dict.items()}
print(transformed)Output: {'A': 200, 'B': 50, 'C': 600, 'D': 20}
17. List‑to‑dict with default values
# Provide "Unknown" for missing values
keys = ["name", "age", "city"]
values = ["Zhang San", 25]
list_to_dict = {key: values[i] if i < len(values) else "Unknown" for i, key in enumerate(keys)}
print(list_to_dict)Output: {'name': 'Zhang San', 'age': 25, 'city': 'Unknown'}
18. Tuple‑to‑dict with default values
# Convert tuple of pairs, keep existing values
tuples = (("name", "Zhang San"), ("age", 25), ("city", "Beijing"))
tuple_to_dict = {k: v for k, v in tuples}
print(tuple_to_dict)Output: {'name': 'Zhang San', 'age': 25, 'city': 'Beijing'}
19. Sort a dictionary by value
# Sort ascending by value
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)Output: {'d': 10, 'b': 25, 'a': 100, 'c': 300}
20. Remove duplicate values
# Keep only keys whose values are unique
my_dict = {"a": 100, "b": 100, "c": 300, "d": 10}
unique = {k: v for k, v in my_dict.items() if list(my_dict.values()).count(v) == 1}
print(unique)Output: {'c': 300, 'd': 10}
21. Check if a key exists
# Membership test
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
key = "b"
if key in my_dict:
print(f"Key '{key}' exists")
else:
print(f"Key '{key}' does not exist")Output: Key 'b' exists
22. Find key with maximum value
# max() with key argument
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
max_key = max(my_dict, key=my_dict.get)
print(f"Key with max value: {max_key}")Output: Key with max value: c
23. Find key with minimum value
# min() with key argument
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
min_key = min(my_dict, key=my_dict.get)
print(f"Key with min value: {min_key}")Output: Key with min value: d
24. Clear a dictionary
# Remove all items
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
my_dict.clear()
print(my_dict)Output: {}
25. Copy a dictionary
# Shallow copy
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
copy_dict = my_dict.copy()
print(copy_dict)Output: {'a': 100, 'b': 25, 'c': 300, 'd': 10}
26. Update a dictionary
# Merge another mapping
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
updates = {"b": 30, "e": 50}
my_dict.update(updates)
print(my_dict)Output: {'a': 100, 'b': 30, 'c': 300, 'd': 10, 'e': 50}
27. Use get() with default
# Safe retrieval
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
value = my_dict.get("b", "Key not found")
print(value)Output: 25
28. Use setdefault() to add a key
# Insert only if missing
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
my_dict.setdefault("e", 50)
print(my_dict)Output: {'a': 100, 'b': 25, 'c': 300, 'd': 10, 'e': 50}
29. Remove a key with pop()
# pop returns the removed value
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
removed = my_dict.pop("b", "Key not found")
print(f"Removed value: {removed}")
print(my_dict)Output:
Removed value: 25
{'a': 100, 'c': 300, 'd': 10}
30. Remove an arbitrary item with popitem()
# popitem removes the last inserted pair (Python 3.7+)
my_dict = {"a": 100, "b": 25, "c": 300, "d": 10}
item = my_dict.popitem()
print(f"Removed item: {item}")
print(my_dict)Output:
Removed item: ('d', 10)
{'a': 100, 'b': 25, 'c': 300}
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
