
# Introduction
Dictionaries in Python are helpful for every little thing from configs, JSON knowledge, to API responses. Most newcomers solely be taught the fundamentals, like making a dictionary, accessing a key, and updating a price. That is it. Nonetheless, there’s much more to dictionaries than that. On this article, we’ll undergo 7 suggestions that may make your code cleaner and extra Pythonic. So, let’s get began.
# Utilizing .get() As a substitute of [] for Lookups
For example that you’re working with a dictionary and it is advisable entry a price. However what if the secret is not there? For example we now have a config dictionary and also you attempt to print the "timeout" key like this:
config = {"debug": True, "verbose": False}
print(config["timeout"])
Output:
---------------------------------------------------------------------------
KeyError Traceback (most up-to-date name final)
----> 2 print(config["timeout"])
KeyError: 'timeout'
It will fail. You’ll get a KeyError as a result of "timeout" is not within the dictionary. As a substitute, it is best to use the .get() methodology. It is safer and you may set a default worth if the secret is lacking.
config = {"debug": True, "verbose": False}
print(config.get("timeout", 30))
Output:
It will print 30, which is the default worth we set. Nonetheless, if a lacking key’s a bug, use sq. brackets. You need the error to point out up straight away in that case.
# Utilizing defaultdict for Grouping Knowledge
In the event you’re working with an inventory of phrases and also you need to depend what number of occasions every phrase seems, you would possibly code it like this:
phrases = ["apple", "banana", "apple", "cherry", "banana", "banana"]
counts = {}
for phrase in phrases:
if phrase not in counts:
counts[word] = 0
counts[word] += 1
print(counts)
Output:
{'apple': 2, 'banana': 3, 'cherry': 1}
This works, however it’s kind of verbose. Python’s defaultdict makes it cleaner:
from collections import defaultdict
phrases = ["apple", "banana", "apple", "cherry", "banana", "banana"]
counts = defaultdict(int)
for phrase in phrases:
counts[word] += 1
print(counts)
Output:
defaultdict(, {'apple': 2, 'banana': 3, 'cherry': 1})
As a result of we used defaultdict(int), Python mechanically creates a default worth of 0 every time a lacking key’s accessed.
# Merging Dictionaries With the | Operator
In trendy Python, the cleanest option to merge dictionaries is with the | operator.
defaults = {"coloration": "blue", "measurement": "medium"}
overrides = {"measurement": "massive", "weight": "heavy"}
merged = defaults | overrides
print(merged)
Output:
{'coloration': 'blue', 'measurement': 'massive', 'weight': 'heavy'}
When keys overlap, the dictionary on the suitable facet wins. If you wish to do in-place merging, you should use the |= operator:
defaults |= overrides
print(defaults)
Output:
{'coloration': 'blue', 'measurement': 'massive', 'weight': 'heavy'}
# Unpacking Dictionaries into Perform Arguments
For example you’ve a perform and a dictionary, and their fields or keys match. As a substitute of passing the keys one after the other, like identify=knowledge["name"], age=knowledge["age"], you possibly can move every little thing utilizing the ** double-asterisk operator. Let’s create a consumer perform and a few dummy consumer knowledge to know it:
def create_user(identify, age, function="viewer"):
return {"identify": identify, "age": age, "function": function}
user_data = {
"identify": "David",
"age": 33
}
# Regular Approach
consumer = create_user(
identify=user_data["name"],
age=user_data["age"],
function=user_data["role"]
)
print(consumer)
Output:
{'identify': 'David', 'age': 33, 'function': 'viewer'}
# Utilizing **
print(create_user(**user_data))
Output:
{'identify': 'David', 'age': 33, 'function': 'viewer'}
Notice that the “Regular Approach” instance above will elevate a >KeyError as a result of user_data doesn’t include a "function" key. The ** unpacking strategy appropriately falls again to the perform’s default worth for function, making it each cleaner and extra sturdy.
# Utilizing the Walrus Operator With Dicts
Python 3.8 launched the walrus operator (:=), which helps you to assign a price as a part of an expression. That is actually helpful with dictionaries.
For example you’ve a dictionary and also you need to get the consumer knowledge and their identify in the event that they exist. That is sometimes how you’ll usually code it:
knowledge = {
"consumer": {
"identify": "Bryan",
"e-mail": "bryan@gmail.com"
}
}
if knowledge.get("consumer") isn't None:
consumer = knowledge.get("consumer")
identify = consumer.get("identify")
print(identify)
Output:
This works, nevertheless it repeats the identical dictionary lookup a number of occasions. You possibly can change it with the walrus operator (:=), which seems to be up and assigns the worth in a single step:
if (consumer := knowledge.get("consumer")) isn't None:
identify = consumer.get("identify")
print(identify)
Output:
That is particularly useful when working with nested dictionary buildings.
# Utilizing TypedDict for Structured Knowledge
Dictionaries are versatile, however that flexibility can typically grow to be an issue. For instance:
def greet(consumer):
return f"Howdy, {consumer['name']}!"
consumer = {
"identify": "Clair",
"age": "thirty"
}
print(greet(consumer))
Output:
This works at runtime, however there’s a hidden drawback: "age" is meant to be a quantity, not a string. Python itself won’t complain, which might result in bugs later in bigger tasks. TypedDict makes the anticipated dictionary construction express:
from typing import TypedDict
class UserProfile(TypedDict):
identify: str
age: int
def greet(consumer: UserProfile) -> str:
return f"Howdy, {consumer['name']}!"
Now instruments like mypy can catch errors earlier than the code runs:
consumer: UserProfile = {
"identify": "Clair",
"age": "thirty",
}
print(greet(consumer))
Output:
check.py:15: error: Incompatible varieties (expression has sort "str", TypedDict merchandise "age" has sort "int") [typeddict-item]
Discovered 1 error in 1 file (checked 1 supply file)
For extra advanced validation, instruments like dataclasses or Pydantic are sometimes higher decisions.
# Iterating Simply: .objects(), .keys(), .values()
Python dictionaries have many built-in strategies for iteration: .objects(), .keys(), and .values(). Most builders learn about them, however do not use them as usually as they need to. They could loop over a dictionary like this:
scores = {
"David": 92,
"Bryan": 87,
"Clair": 95
}
for identify in scores:
print(identify, scores[name])
Output:
David 92
Bryan 87
Clair 95
That works. However it’s not one of the best ways — it does an additional dictionary lookup each time via the loop. Python’s .objects() methodology is cleaner:
for identify, rating in scores.objects():
print(identify, rating)
Output:
David 92
Bryan 87
Clair 95
It returns each the important thing and worth collectively, which avoids repeated lookups and makes the code extra readable. In the event you solely want the keys, use .keys() as a substitute. Equally, if you happen to solely want the values, use .values().
# Wrapping Up
Python dictionaries look easy at first, however studying a couple of key patterns could make your code a lot cleaner. You need to use this hyperlink to be taught extra in regards to the capabilities related to Python dictionaries. Options like .get(), defaultdict, unpacking, and TypedDict assist cut back repetitive code and make your applications extra dependable.
Kanwal Mehreen is a machine studying engineer and a technical author with a profound ardour for knowledge science and the intersection of AI with drugs. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions range and educational excellence. She’s additionally acknowledged as a Teradata Variety in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower girls in STEM fields.

# Introduction
Dictionaries in Python are helpful for every little thing from configs, JSON knowledge, to API responses. Most newcomers solely be taught the fundamentals, like making a dictionary, accessing a key, and updating a price. That is it. Nonetheless, there’s much more to dictionaries than that. On this article, we’ll undergo 7 suggestions that may make your code cleaner and extra Pythonic. So, let’s get began.
# Utilizing .get() As a substitute of [] for Lookups
For example that you’re working with a dictionary and it is advisable entry a price. However what if the secret is not there? For example we now have a config dictionary and also you attempt to print the "timeout" key like this:
config = {"debug": True, "verbose": False}
print(config["timeout"])
Output:
---------------------------------------------------------------------------
KeyError Traceback (most up-to-date name final)
----> 2 print(config["timeout"])
KeyError: 'timeout'
It will fail. You’ll get a KeyError as a result of "timeout" is not within the dictionary. As a substitute, it is best to use the .get() methodology. It is safer and you may set a default worth if the secret is lacking.
config = {"debug": True, "verbose": False}
print(config.get("timeout", 30))
Output:
It will print 30, which is the default worth we set. Nonetheless, if a lacking key’s a bug, use sq. brackets. You need the error to point out up straight away in that case.
# Utilizing defaultdict for Grouping Knowledge
In the event you’re working with an inventory of phrases and also you need to depend what number of occasions every phrase seems, you would possibly code it like this:
phrases = ["apple", "banana", "apple", "cherry", "banana", "banana"]
counts = {}
for phrase in phrases:
if phrase not in counts:
counts[word] = 0
counts[word] += 1
print(counts)
Output:
{'apple': 2, 'banana': 3, 'cherry': 1}
This works, however it’s kind of verbose. Python’s defaultdict makes it cleaner:
from collections import defaultdict
phrases = ["apple", "banana", "apple", "cherry", "banana", "banana"]
counts = defaultdict(int)
for phrase in phrases:
counts[word] += 1
print(counts)
Output:
defaultdict(, {'apple': 2, 'banana': 3, 'cherry': 1})
As a result of we used defaultdict(int), Python mechanically creates a default worth of 0 every time a lacking key’s accessed.
# Merging Dictionaries With the | Operator
In trendy Python, the cleanest option to merge dictionaries is with the | operator.
defaults = {"coloration": "blue", "measurement": "medium"}
overrides = {"measurement": "massive", "weight": "heavy"}
merged = defaults | overrides
print(merged)
Output:
{'coloration': 'blue', 'measurement': 'massive', 'weight': 'heavy'}
When keys overlap, the dictionary on the suitable facet wins. If you wish to do in-place merging, you should use the |= operator:
defaults |= overrides
print(defaults)
Output:
{'coloration': 'blue', 'measurement': 'massive', 'weight': 'heavy'}
# Unpacking Dictionaries into Perform Arguments
For example you’ve a perform and a dictionary, and their fields or keys match. As a substitute of passing the keys one after the other, like identify=knowledge["name"], age=knowledge["age"], you possibly can move every little thing utilizing the ** double-asterisk operator. Let’s create a consumer perform and a few dummy consumer knowledge to know it:
def create_user(identify, age, function="viewer"):
return {"identify": identify, "age": age, "function": function}
user_data = {
"identify": "David",
"age": 33
}
# Regular Approach
consumer = create_user(
identify=user_data["name"],
age=user_data["age"],
function=user_data["role"]
)
print(consumer)
Output:
{'identify': 'David', 'age': 33, 'function': 'viewer'}
# Utilizing **
print(create_user(**user_data))
Output:
{'identify': 'David', 'age': 33, 'function': 'viewer'}
Notice that the “Regular Approach” instance above will elevate a >KeyError as a result of user_data doesn’t include a "function" key. The ** unpacking strategy appropriately falls again to the perform’s default worth for function, making it each cleaner and extra sturdy.
# Utilizing the Walrus Operator With Dicts
Python 3.8 launched the walrus operator (:=), which helps you to assign a price as a part of an expression. That is actually helpful with dictionaries.
For example you’ve a dictionary and also you need to get the consumer knowledge and their identify in the event that they exist. That is sometimes how you’ll usually code it:
knowledge = {
"consumer": {
"identify": "Bryan",
"e-mail": "bryan@gmail.com"
}
}
if knowledge.get("consumer") isn't None:
consumer = knowledge.get("consumer")
identify = consumer.get("identify")
print(identify)
Output:
This works, nevertheless it repeats the identical dictionary lookup a number of occasions. You possibly can change it with the walrus operator (:=), which seems to be up and assigns the worth in a single step:
if (consumer := knowledge.get("consumer")) isn't None:
identify = consumer.get("identify")
print(identify)
Output:
That is particularly useful when working with nested dictionary buildings.
# Utilizing TypedDict for Structured Knowledge
Dictionaries are versatile, however that flexibility can typically grow to be an issue. For instance:
def greet(consumer):
return f"Howdy, {consumer['name']}!"
consumer = {
"identify": "Clair",
"age": "thirty"
}
print(greet(consumer))
Output:
This works at runtime, however there’s a hidden drawback: "age" is meant to be a quantity, not a string. Python itself won’t complain, which might result in bugs later in bigger tasks. TypedDict makes the anticipated dictionary construction express:
from typing import TypedDict
class UserProfile(TypedDict):
identify: str
age: int
def greet(consumer: UserProfile) -> str:
return f"Howdy, {consumer['name']}!"
Now instruments like mypy can catch errors earlier than the code runs:
consumer: UserProfile = {
"identify": "Clair",
"age": "thirty",
}
print(greet(consumer))
Output:
check.py:15: error: Incompatible varieties (expression has sort "str", TypedDict merchandise "age" has sort "int") [typeddict-item]
Discovered 1 error in 1 file (checked 1 supply file)
For extra advanced validation, instruments like dataclasses or Pydantic are sometimes higher decisions.
# Iterating Simply: .objects(), .keys(), .values()
Python dictionaries have many built-in strategies for iteration: .objects(), .keys(), and .values(). Most builders learn about them, however do not use them as usually as they need to. They could loop over a dictionary like this:
scores = {
"David": 92,
"Bryan": 87,
"Clair": 95
}
for identify in scores:
print(identify, scores[name])
Output:
David 92
Bryan 87
Clair 95
That works. However it’s not one of the best ways — it does an additional dictionary lookup each time via the loop. Python’s .objects() methodology is cleaner:
for identify, rating in scores.objects():
print(identify, rating)
Output:
David 92
Bryan 87
Clair 95
It returns each the important thing and worth collectively, which avoids repeated lookups and makes the code extra readable. In the event you solely want the keys, use .keys() as a substitute. Equally, if you happen to solely want the values, use .values().
# Wrapping Up
Python dictionaries look easy at first, however studying a couple of key patterns could make your code a lot cleaner. You need to use this hyperlink to be taught extra in regards to the capabilities related to Python dictionaries. Options like .get(), defaultdict, unpacking, and TypedDict assist cut back repetitive code and make your applications extra dependable.
Kanwal Mehreen is a machine studying engineer and a technical author with a profound ardour for knowledge science and the intersection of AI with drugs. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions range and educational excellence. She’s additionally acknowledged as a Teradata Variety in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower girls in STEM fields.















