Sunday, June 21, 2026

Python Dictionary Ideas and Methods You Ought to All the time Bear in mind


 

Introduction

 
Dictionaries in Python are helpful for all the things from configs, JSON knowledge, to API responses. Most novices solely study 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 ideas that may make your code cleaner and extra Pythonic. So, let’s get began.

 

Utilizing .get() As an alternative of [] for Lookups

 
For example that you’re working with a dictionary and it’s essential entry a price. However what if the hot button is not there? For example we have now 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'

 

This may fail. You’re going to get a KeyError as a result of "timeout" is not within the dictionary. As an alternative, you must use the .get() methodology. It is safer and you may set a default worth if the hot button is lacking.

config = {"debug": True, "verbose": False}

print(config.get("timeout", 30))

 

Output:

 

This may print 30, which is the default worth we set. Nonetheless, if a lacking secret is a bug, use sq. brackets. You need the error to indicate up immediately in that case.

 

Utilizing defaultdict for Grouping Information

 
In case you’re working with a listing of phrases and also you need to rely 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 is a bit 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 robotically creates a default worth of 0 each time a lacking secret is accessed.

 

Merging Dictionaries With the | Operator

 
In trendy Python, the cleanest approach to merge dictionaries is with the | operator.

defaults = {"coloration": "blue", "dimension": "medium"}
overrides = {"dimension": "giant", "weight": "heavy"}

merged = defaults | overrides
print(merged)

 

Output:

{'coloration': 'blue', 'dimension': 'giant', 'weight': 'heavy'}

 

When keys overlap, the dictionary on the best aspect wins. If you wish to do in-place merging, you should utilize the |= operator:

defaults |= overrides
print(defaults)

 

Output:

{'coloration': 'blue', 'dimension': 'giant', 'weight': 'heavy'}

 

Unpacking Dictionaries into Operate Arguments

 
For example you might have a perform and a dictionary, and their fields or keys match. As an alternative of passing the keys one after the other, like identify=knowledge["name"], age=knowledge["age"], you possibly can move all the things utilizing the ** double-asterisk operator. Let’s create a person perform and a few dummy person knowledge to grasp it:

def create_user(identify, age, function="viewer"):
    return {"identify": identify, "age": age, "function": function}

user_data = {
    "identify": "David",
    "age": 33
}

 

# Regular Means
person = create_user(
    identify=user_data["name"],
    age=user_data["age"],
    function=user_data["role"]
)

print(person)

 

Output:

{'identify': 'David', 'age': 33, 'function': 'viewer'}

 

# Utilizing **
print(create_user(**user_data))

 

Output:

{'identify': 'David', 'age': 33, 'function': 'viewer'}

 

Observe that the “Regular Means” instance above will elevate a >KeyError as a result of user_data doesn’t include a "function" key. The ** unpacking method accurately falls again to the perform’s default worth for function, making it each cleaner and extra strong.

 

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 might have a dictionary and also you need to get the person knowledge and their identify in the event that they exist. That is usually how you’d usually code it:

knowledge = {
    "person": {
        "identify": "Bryan",
        "e mail": "bryan@gmail.com"
    }
}

if knowledge.get("person") just isn't None:
    person = knowledge.get("person")
    identify = person.get("identify")

    print(identify)

 

Output:

 

This works, but it surely repeats the identical dictionary lookup a number of occasions. You possibly can change it with the walrus operator (:=), which appears up and assigns the worth in a single step:

if (person := knowledge.get("person")) just isn't None:
    identify = person.get("identify")

    print(identify)

 

Output:

 

That is particularly useful when working with nested dictionary buildings.

 

Utilizing TypedDict for Structured Information

 
Dictionaries are versatile, however that flexibility can typically develop into an issue. For instance:

def greet(person):
    return f"Hey, {person['name']}!"

person = {
    "identify": "Clair",
    "age": "thirty"
}

print(greet(person))

 

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 specific:

from typing import TypedDict

class UserProfile(TypedDict):
    identify: str
    age: int

def greet(person: UserProfile) -> str:
    return f"Hey, {person['name']}!"

 

Now instruments like mypy can catch errors earlier than the code runs:

person: UserProfile = {
    "identify": "Clair",
    "age": "thirty",
}

print(greet(person))

 

Output:

check.py:15: error: Incompatible sorts (expression has kind "str", TypedDict merchandise "age" has kind "int")  [typeddict-item]
Discovered 1 error in 1 file (checked 1 supply file)

 

For extra complicated 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 typically as they need to. They may 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 by way of 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 case you solely want the keys, use .keys() as an alternative. Equally, in the event you 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 study extra concerning the capabilities related to Python dictionaries. Options like .get(), defaultdict, unpacking, and TypedDict assist scale back repetitive code and make your packages 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 tutorial excellence. She’s additionally acknowledged as a Teradata Range in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower ladies in STEM fields.

Related Articles

Latest Articles