Dictionaries are the workhorse data structure in Python. Settings, user records, product details, counts, and parsed JSON all end up as dictionaries: a collection of keys, each pointing to a value. You look things up by name instead of by position, which makes the code read closer to how you think about the data.
Knowing the basic creation syntax is only the start. The real productivity comes from a handful of python dictionary methods that handle everyday jobs safely: fetching a value that might not exist, merging two dictionaries, looping over keys and values together, and counting things without a pile of if statements. This guide collects those patterns in one place with short examples you can adapt.
If you enjoy compact Python patterns, this article sits naturally next to the guide on Python list comprehensions, because dictionary comprehensions use the same idea and the two structures are constantly converted into each other in real code.
Creating Dictionaries and Accessing Values
The most common way to create a dictionary is with curly braces and colon-separated pairs. Keys are usually strings in everyday code, though numbers and tuples can be keys too. Values can be anything: numbers, strings, lists, or other dictionaries.
user = {
"name": "Sara",
"role": "editor",
"logins": 42
}
print(user["name"]) # Sara
print(user["role"]) # editor
Square brackets with the key inside fetch the value stored under that key. This works well when you are certain the key exists. The risk is a missing key: Python raises a KeyError and your program stops. For data you control completely, that strict behaviour is fine and even helpful, because it surfaces mistakes early. For data that comes from a user, a file, or an API, you need a gentler approach, covered in the next section.
You can add or replace entries with the same bracket syntax. If the key is new, it is added. If it already exists, its value is overwritten.
user["role"] = "senior editor" user["active"] = True print(user)
After these two lines the dictionary has an updated role and a new active entry. There is no append method for dictionaries because position does not matter; you simply assign by key. Deleting uses the del statement with a key, or the pop method described later when you also need the removed value.
Safe Lookups With get and setdefault
The get method is the single most useful dictionary method for defensive code. It returns the value for a key if present, and a default you choose if not, instead of raising an error.
settings = {"theme": "dark", "font_size": 14}
theme = settings.get("theme", "light")
language = settings.get("language", "en")
print(theme) # dark
print(language) # en
The first call finds theme in the dictionary and returns dark, ignoring the default. The second call cannot find language, so it returns the default en. Your code continues without a try block or a membership test. Choosing sensible defaults is part of the craft: an empty string, zero, or an empty list are common choices depending on what the code does next.
A close relative is setdefault. It looks up a key, and if the key is missing it first inserts the default into the dictionary, then returns it. That makes it ideal for building groups, such as collecting names under team labels.
teams = {}
teams.setdefault("design", []).append("Mia")
teams.setdefault("design", []).append("Leo")
teams.setdefault("code", []).append("Ana")
print(teams) # {'design': ['Mia', 'Leo'], 'code': ['Ana']}
Each call guarantees that the key exists with a list as its value. If the key was absent, an empty list is inserted and then append adds the name to it. If the key was already there, setdefault returns the existing list untouched. Without this method you would need an if test before every append, so setdefault removes a whole category of repetitive checks when grouping data.
Looping Over Keys, Values, and Pairs
Looping over a dictionary directly gives you its keys. When you need values as well, the items method returns key and value pairs that you can unpack in the loop header. The keys and values methods are available when you only need one side.
prices = {"pen": 2, "pad": 5, "mug": 8}
for item, price in prices.items():
print(item, "costs", price)
The loop unpacks each pair into item and price, so the body can use both without extra lookups. This is cleaner and faster than looping over keys and then fetching each value with brackets. The order of the pairs follows insertion order, a guarantee in modern Python, so dictionaries remember the sequence in which keys were first added. That makes them suitable for ordered configuration and for reports where output order matters.
Sometimes you need to loop and build a new dictionary rather than print. That is where a dictionary comprehension shines, for example applying a discount to every price or filtering out zero stock.
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted) # {'pen': 1.8, 'pad': 4.5, 'mug': 7.2}
The comprehension unpacks each pair, multiplies the price, and stores the result under the same key in a new dictionary. The original prices dictionary is unchanged, which keeps the code predictable. The same filtering idea from list comprehensions applies here too, as shown in the list comprehensions guide for the list version of this pattern.
Merging and Updating Dictionaries
Programs often combine dictionaries: default settings plus user settings, or two partial records about the same product. The update method merges one dictionary into another in place. When keys overlap, the incoming value wins.
defaults = {"theme": "light", "font_size": 12, "sound": True}
user_prefs = {"theme": "dark", "font_size": 14}
defaults.update(user_prefs)
print(defaults) # {'theme': 'dark', 'font_size': 14, 'sound': True}
After the update, theme and font_size reflect the user choices, while sound keeps its default because the user dictionary did not mention it. This defaults-plus-overrides pattern is one of the most practical uses of dictionaries in configuration handling. Note that update changes the dictionary it is called on. If you need to keep both originals intact, build a new dictionary with the unpacking operator.
base = {"host": "localhost", "port": 8000}
override = {"port": 9000}
config = {**base, **override}
print(config) # {'host': 'localhost', 'port': 9000}
The double asterisk unpacks each dictionary into the new one in order. Because override comes second, its port value replaces the one from base. The result is a fresh dictionary and neither input is modified. In newer Python versions the pipe operator can merge dictionaries in a similar way, creating a new dictionary where the right side wins on duplicate keys. Either approach reads well; pick one and stay consistent in a project.
Merging is also how you typically handle JSON-style data returned from the web. A response parsed into a dictionary can be combined with local defaults before your code uses it, which connects this topic with making HTTP requests in Python, where responses are handled as dictionaries almost every time.
Removing Values: pop, popitem, and clear
The pop method removes a key and returns its value, which is useful when a value should be used once and then discarded, such as a one-time token or a task taken from a queue stored as a dictionary.
tasks = {"a1": "email report", "b2": "fix header"}
job = tasks.pop("a1")
print(job) # email report
print(tasks) # {'b2': 'fix header'}
Like bracket access, pop raises a KeyError for a missing key, but it accepts an optional second argument as a fallback. Passing None as that fallback lets you attempt a removal without checking first. The popitem method removes and returns the most recently added pair, which can serve simple last-in, first-out patterns. The clear method empties a dictionary entirely while keeping the same object, which matters when other variables refer to that same dictionary elsewhere in the program.
cache = {"x": 1, "y": 2}
last = cache.popitem()
print(last) # ('y', 2)
cache.clear()
print(cache) # {}
Here popitem returns the y pair as a tuple, and clear then removes what remains. Knowing which removal method fits the situation keeps the code short: pop for a known key, pop with a default for a maybe key, popitem for the latest entry, and clear when you want a clean slate without creating a new object.
Counting and Grouping Patterns
Counting occurrences is a classic dictionary job. The straightforward approach uses get with a default of zero, so each new item starts at zero and is incremented.
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts) # {'red': 3, 'blue': 2, 'green': 1}
For each word, get returns the current count or zero if the word has not been seen. Adding one and storing the result builds the tally. This pattern works for counting file extensions, votes, error types in a log, and any other frequency job. Python’s collections module offers a Counter class that does this in one line, and it is worth learning after you understand the manual pattern, because the manual version appears in interviews and in codebases that avoid extra imports.
Grouping follows the setdefault pattern from earlier. A related tool is collections.defaultdict, which creates missing values automatically using a factory such as list or int. Even if you use defaultdict in larger projects, the get and setdefault versions remain valuable because they work anywhere without imports and make the default value visible right where it is used.
These counting techniques also pair with reading data from files. Counting words in a text file, for instance, combines the file reading steps from the Python file handling guide with the get pattern above: read lines, split into words, and tally each one in a dictionary.
Checking Membership and Handling Nested Data
The in operator tests whether a key exists. It checks keys, not values, which is a common point of confusion for beginners who expect it to search everything.
inventory = {"pens": 12, "pads": 5}
print("pens" in inventory) # True
print("rulers" in inventory) # False
print(12 in inventory) # False, 12 is a value not a key
If you truly need to search values, use in with the values method explicitly, as in 12 in inventory.values(). In most designs, though, needing to search by value repeatedly is a hint that the dictionary should be structured the other way around, with the searched field as the key.
Real data is often nested: a dictionary containing lists, or dictionaries inside dictionaries, like a user record with an address block.
order = {
"id": 101,
"customer": {"name": "Omar", "city": "Leeds"},
"items": ["pen", "pad"]
}
print(order["customer"]["city"]) # Leeds
print(order.get("customer", {}).get("postcode", "unknown"))
The first lookup chains brackets because the structure is known. The second chain uses get with an empty dictionary as the default for the first step, so a missing customer block returns unknown instead of raising an error. This chained get pattern is a safe way to dig into data whose shape you do not fully control, such as responses from external services or configuration files written by hand.
Conclusion
Most dictionary work in Python comes down to a short list of moves: bracket access when a key is guaranteed, get when it is not, setdefault for grouping, items for looping over pairs, update or unpacking for merging, and pop for removal. Learn those python dictionary methods well and you can handle settings, counts, records, and parsed JSON with confidence, using code that stays short without becoming fragile.
Tagged: python data structures python dict python dictionary methods python get method python snippets python tricks



3 thoughts on “Working With Dictionaries in Python: Everyday Methods and Tricks”