Python dictionaries are one of the most powerful and frequently used data structures in Python. They let you store information as key-value pairs, making it easy to look up, update, transform, group, and organize data.
Modern Python provides several elegant dictionary techniques that can replace verbose code with short, readable expressions.
In this guide, you’ll learn 25+ Python Dictionary tricks, from beginner shortcuts to professional techniques used in real-world Python development.
What Is a Python Dictionary?
A dictionary stores data using the structure:
dictionary = {
"key": "value"
}
Example:
user = {
"name": "Alex",
"age": 21,
"language": "Python"
}
You can access values using their keys:
print(user["name"])
Output:
Alex
Dictionary keys must be hashable, and dictionaries preserve insertion order in modern Python.
1. Create a Dictionary in One Line
Instead of writing multiple assignments:
user = {}
user["name"] = "Alex"
user["age"] = 21
user["language"] = "Python"
Use a dictionary literal:
user = {
"name": "Alex",
"age": 21,
"language": "Python"
}
Shortcut
user = dict(name="Alex", age=21, language="Python")
This is especially convenient when your keys are simple strings.
2. Safely Get a Dictionary Value
This can cause an error:
user = {"name": "Alex"}
print(user["email"])
Result:
KeyError
Use .get() when a key might not exist:
print(user.get("email"))
Result:
None
You can also provide a default:
print(user.get("email", "Not provided"))
Output:
Not provided
Professional pattern
email = user.get("email", "unknown@example.com")
This is cleaner than manually checking whether a key exists.
3. Check Whether a Key Exists
Instead of:
if "name" in user.keys():
print("Found")
Use:
if "name" in user:
print("Found")
This is the idiomatic Python approach.
Remember:
"name" in user
checks keys, not values.
4. Use setdefault() for Missing Values
Suppose you want to create a list for a key only when that key doesn’t exist.
Verbose approach:
data = {}
if "python" not in data:
data["python"] = []
data["python"].append("Dictionaries")
Shortcut:
data = {}
data.setdefault("python", []).append("Dictionaries")
Now:
print(data)
Output:
{'python': ['Dictionaries']}
Why this trick is useful
It is particularly handy for grouping data.
5. Build a Dictionary with Dictionary Comprehension
Dictionary comprehensions are one of Python’s best shortcuts.
Instead of:
numbers = {}
for n in range(1, 6):
numbers[n] = n ** 2
Use:
numbers = {n: n ** 2 for n in range(1, 6)}
Result:
{
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
The general pattern is:
{key: value for item in iterable}
Python officially supports dictionary comprehensions for constructing dictionaries from expressions and loops.
6. Add Conditions to Dictionary Comprehensions
You can filter values directly:
numbers = {
n: n ** 2
for n in range(1, 11)
if n % 2 == 0
}
Result:
{
2: 4,
4: 16,
6: 36,
8: 64,
10: 100
}
Pattern
{key: value for item in iterable if condition}
This is extremely useful for data cleaning and filtering.
7. Reverse Keys and Values
Suppose:
data = {
"a": 1,
"b": 2,
"c": 3
}
Reverse it with:
reversed_data = {
value: key
for key, value in data.items()
}
Result:
{
1: "a",
2: "b",
3: "c"
}
Important
This only works safely when the values are unique and hashable.
If two keys have the same value, one entry will overwrite another.
8. Loop Through Keys and Values Together
Instead of:
for key in user:
print(key, user[key])
Use:
for key, value in user.items():
print(key, value)
Example:
user = {
"name": "Alex",
"age": 21
}
for key, value in user.items():
print(f"{key}: {value}")
Output:
name: Alex
age: 21
9. Get Only Keys
keys = user.keys()
Or create a list:
keys = list(user)
Example:
user = {
"name": "Alex",
"age": 21
}
print(list(user))
Output:
['name', 'age']
10. Get Only Values
Use:
values = user.values()
For a list:
values = list(user.values())
Example:
prices = {
"book": 20,
"pen": 5,
"bag": 40
}
print(list(prices.values()))
Output:
[20, 5, 40]
11. Merge Two Dictionaries
Modern Python shortcut
Python 3.9 introduced the dictionary merge operator | and update operator |=.
user = {
"name": "Alex",
"age": 21
}
extra = {
"language": "Python",
"level": "Advanced"
}
combined = user | extra
Result:
{
"name": "Alex",
"age": 21,
"language": "Python",
"level": "Advanced"
}
This creates a new dictionary.
12. Update a Dictionary with |=
If you want to modify the existing dictionary:
user |= extra
Now user itself contains the additional keys.
Quick comparison
a | b
→ creates a new dictionary.
a |= b
→ updates a.
13. Merge Dictionaries with **
Another useful technique is dictionary unpacking:
combined = {
**user,
**extra
}
If duplicate keys exist, later values override earlier values.
Example:
defaults = {
"theme": "dark",
"language": "Python"
}
settings = {
"theme": "light"
}
final = {
**defaults,
**settings
}
Result:
{
"theme": "light",
"language": "Python"
}
14. Create a Dictionary from Two Lists
Suppose:
keys = ["name", "age", "language"]
values = ["Alex", 21, "Python"]
Instead of manually constructing the dictionary:
data = dict(zip(keys, values))
Result:
{
"name": "Alex",
"age": 21,
"language": "Python"
}
This is a very useful shortcut:
dict(zip(keys, values))
15. Convert a List of Pairs into a Dictionary
Given:
items = [
("Python", 1),
("JavaScript", 2),
("Java", 3)
]
Simply use:
data = dict(items)
Result:
{
"Python": 1,
"JavaScript": 2,
"Java": 3
}
Python’s dict() constructor supports creating dictionaries from sequences of key-value pairs.
16. Sort a Dictionary by Value
Suppose:
scores = {
"Alex": 85,
"Sam": 92,
"John": 78
}
Sort by values:
sorted_scores = dict(
sorted(
scores.items(),
key=lambda item: item[1]
)
)
Result:
{
"John": 78,
"Alex": 85,
"Sam": 92
}
For descending order:
sorted_scores = dict(
sorted(
scores.items(),
key=lambda item: item[1],
reverse=True
)
)
17. Sort a Dictionary by Key
data = {
"banana": 3,
"apple": 5,
"orange": 2
}
sorted_data = dict(sorted(data.items()))
Result:
{
"apple": 5,
"banana": 3,
"orange": 2
}
18. Find the Key with the Maximum Value
Instead of sorting the entire dictionary:
scores = {
"Alex": 85,
"Sam": 92,
"John": 78
}
winner = max(scores, key=scores.get)
Result:
Sam
Why this is a great trick
If you only need the highest-scoring key, sorting everything is unnecessary.
Use:
max(data, key=data.get)
19. Find the Minimum Value Key
Similarly:
lowest = min(scores, key=scores.get)
Result:
John
Memorize these
max(data, key=data.get)
Highest value key.
min(data, key=data.get)
Lowest value key.
20. Filter a Dictionary
Suppose you only want scores greater than 80:
scores = {
"Alex": 85,
"Sam": 92,
"John": 78
}
high_scores = {
name: score
for name, score in scores.items()
if score > 80
}
Result:
{
"Alex": 85,
"Sam": 92
}
This is one of the most useful dictionary comprehension patterns.
21. Transform Dictionary Values
Suppose:
prices = {
"book": 100,
"pen": 20,
"bag": 500
}
Apply a 10% increase:
new_prices = {
item: price * 1.10
for item, price in prices.items()
}
Result:
{
"book": 110.0,
"pen": 22.0,
"bag": 550.0
}
22. Transform Dictionary Keys
You can transform keys just as easily:
data = {
"Python": 95,
"Java": 80,
"C++": 85
}
lowercase = {
key.lower(): value
for key, value in data.items()
}
Result:
{
"python": 95,
"java": 80,
"c++": 85
}
23. Remove a Key Safely
This can fail:
del user["email"]
if "email" doesn’t exist.
Safer:
user.pop("email", None)
The second argument prevents a KeyError.
Example:
user = {
"name": "Alex"
}
user.pop("email", None)
No error occurs.
24. Remove Several Keys
Instead of repeatedly calling pop():
remove = {"age", "email"}
user = {
key: value
for key, value in user.items()
if key not in remove
}
This creates a filtered dictionary without the unwanted keys.
25. Get Multiple Dictionary Values
Suppose:
user = {
"name": "Alex",
"age": 21,
"language": "Python"
}
You can use:
name, age = user["name"], user["age"]
Or safely:
name, age = user.get("name"), user.get("age")
For many fields, a comprehension can be convenient:
fields = ["name", "language"]
result = {
key: user.get(key)
for key in fields
}
Result:
{
"name": "Alex",
"language": "Python"
}
26. Group Data with setdefault()
Imagine:
students = [
("Alex", "Python"),
("Sam", "Python"),
("John", "Java"),
("Mike", "Java")
]
You can group them:
groups = {}
for name, language in students:
groups.setdefault(language, []).append(name)
Result:
{
"Python": ["Alex", "Sam"],
"Java": ["John", "Mike"]
}
This is a powerful real-world dictionary technique.
27. Count Items with Counter
For frequency counting, collections.Counter is often cleaner than manually managing dictionary counts.
from collections import Counter
languages = [
"Python",
"Java",
"Python",
"C++",
"Python",
"Java"
]
counts = Counter(languages)
print(counts)
Result:
Counter({
"Python": 3,
"Java": 2,
"C++": 1
})
collections provides specialized container types such as Counter for common data-handling patterns.
28. Dictionary Lookup Instead of Long if/elif
This is a fantastic professional trick.
Instead of:
if command == "start":
action = "Starting..."
elif command == "stop":
action = "Stopping..."
elif command == "pause":
action = "Pausing..."
Use a dictionary:
actions = {
"start": "Starting...",
"stop": "Stopping...",
"pause": "Pausing..."
}
action = actions.get(command, "Unknown command")
This makes the code easier to extend.
29. Use Functions as Dictionary Values
Dictionary values don’t have to be strings or numbers.
They can be functions.
def add(a, b):
return a + b
def multiply(a, b):
return a * b
operations = {
"add": add,
"multiply": multiply
}
Now:
result = operations["add"](10, 5)
print(result)
Output:
15
This technique is useful for command systems, dispatch tables, calculators, and application logic.
30. Use fromkeys() for Quick Initialization
Create multiple keys with the same initial value:
keys = ["name", "email", "phone"]
data = dict.fromkeys(keys, None)
Result:
{
"name": None,
"email": None,
"phone": None
}
You can also use:
data = dict.fromkeys(keys, "")
Result:
{
"name": "",
"email": "",
"phone": ""
}
31. Use Dictionary Unpacking in Function Calls
Suppose:
user = {
"name": "Alex",
"age": 21
}
And:
def introduce(name, age):
print(f"{name} is {age} years old.")
Instead of:
introduce(user["name"], user["age"])
Use:
introduce(**user)
The ** operator expands dictionary keys into keyword arguments.
32. Create Nested Dictionaries
Dictionaries can contain other dictionaries:
users = {
"alex": {
"age": 21,
"language": "Python"
},
"sam": {
"age": 22,
"language": "Java"
}
}
Access nested data:
print(users["alex"]["language"])
Output:
Python
For complex JSON-like data, nested dictionaries are extremely common.
33. Flatten a Simple Nested Dictionary
Given:
data = {
"user": {
"name": "Alex",
"age": 21
}
}
You can access values directly:
name = data["user"]["name"]
For repeated deep access, consider designing a cleaner data model rather than creating extremely nested dictionaries.
Professional rule: dictionaries are powerful, but excessive nesting can make code difficult to maintain.
34. Use items() with sorted()
A highly reusable pattern:
for key, value in sorted(data.items()):
print(key, value)
Sort by value:
for key, value in sorted(
data.items(),
key=lambda item: item[1]
):
print(key, value)
This pattern is worth memorizing.
35. Dictionary Trick: Last Duplicate Key Wins
Python allows duplicate keys in dictionary literals, but the later value replaces the earlier one.
Example:
data = {
"name": "Alex",
"name": "Sam"
}
Result:
{
"name": "Sam"
}
This behavior can occasionally be useful for overriding defaults, but accidental duplicate keys can also hide bugs.
36. The Ultimate Dictionary Filtering Pattern
Memorize this:
result = {
key: value
for key, value in data.items()
if condition
}
Example:
scores = {
"Alex": 95,
"Sam": 72,
"John": 88,
"Mike": 60
}
passed = {
name: score
for name, score in scores.items()
if score >= 80
}
Result:
{
"Alex": 95,
"John": 88
}
37. The Ultimate Dictionary Transformation Pattern
Memorize:
result = {
key: transform(value)
for key, value in data.items()
}
Example:
prices = {
"book": 100,
"pen": 20,
"bag": 500
}
discounted = {
item: price * 0.9
for item, price in prices.items()
}
This is one of the most useful dictionary-comprehension patterns in Python.
Python Dictionary Cheat Sheet
| Task | Modern Shortcut |
|---|---|
| Create dictionary | {"a": 1, "b": 2} |
| Safe lookup | data.get("key") |
| Safe lookup with default | data.get("key", default) |
| Check key | "key" in data |
| Get keys | data.keys() |
| Get values | data.values() |
| Get pairs | data.items() |
| Remove safely | data.pop("key", None) |
| Merge | a | b |
| Update/merge | a |= b |
| Unpack | {**a, **b} |
| Dictionary comprehension | {k: v for ...} |
| Filter | {k: v for k, v in d.items() if condition} |
| Sort by key | dict(sorted(d.items())) |
| Sort by value | dict(sorted(d.items(), key=lambda x: x[1])) |
| Highest value key | max(d, key=d.get) |
| Lowest value key | min(d, key=d.get) |
| Lists → dictionary | dict(zip(keys, values)) |
| Same default for keys | dict.fromkeys(keys, value) |
| Group values | setdefault() |
| Frequency counting | Counter() |
| Function dispatch | {name: function} |
| Dictionary → function kwargs | function(**data) |
10 Python Dictionary Tricks You Should Memorize
If you want the shortest possible professional cheat sheet, remember these:
1. Safe access
value = data.get("key", default)
2. Check existence
if "key" in data:
3. Transform
{k: transform(v) for k, v in data.items()}
4. Filter
{k: v for k, v in data.items() if condition}
5. Merge
merged = a | b
6. Update
a |= b
7. List → Dictionary
dict(zip(keys, values))
8. Maximum value
max(data, key=data.get)
9. Minimum value
min(data, key=data.get)
10. Safe removal
data.pop("key", None)
Modern Python Dictionary Best Practices
Prefer .get() when a key is optional
username = user.get("username")
rather than unnecessarily catching KeyError.
Prefer dictionary comprehensions for simple transformations
squares = {n: n * n for n in numbers}
But don’t make a comprehension so complicated that a normal for loop becomes easier to read.
Use | for modern dictionary merging
config = defaults | user_config
This clearly communicates that two dictionaries are being combined. The | and |= operators were introduced for dictionaries in Python 3.9.
Use Counter for frequency counting
from collections import Counter
Counter(items)
Don’t overuse nested dictionaries
If your data structure becomes deeply nested, consider whether a class, dataclass, or another structured representation would make the code easier to understand.
Final Thoughts
Python dictionaries go far beyond simple key-value storage. Once you master dictionary comprehensions, .get(), .setdefault(), zip(), items(), Counter, dictionary unpacking, and the modern | merge operator, you can write considerably cleaner and more expressive Python.
The biggest productivity gains come from recognizing common patterns:
{k: v for k, v in data.items()}
{k: v for k, v in data.items() if condition}
a | b
dict(zip(keys, values))
max(data, key=data.get)
These aren’t merely “shortcuts”—they are idiomatic Python patterns that make everyday data processing much more readable.
Python Dictionary mastery = cleaner code + fewer lines + better data handling.

