What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
If posting["salary"] raises KeyError, the mapping you are reading does not contain the key "salary". For an optional field, use posting.get("salary", "Not listed") or another fallback that fits your code. For a required field, keep the missing value visible and report it clearly instead of quietly inventing one.
Why a job-posting lookup raises KeyError
In Python, square brackets request a value by key: posting["salary"]. If that key is absent from the mapping, Python raises KeyError. The exception identifies the missing key, which helps narrow the problem; it does not establish that the posting itself is invalid or that every posting should contain that field. A posting represented as a dictionary after JSON parsing may have a different shape depending on its source. See the Python documentation for built-in mapping types.
A missing key can result from a spelling or capitalization mismatch, looking at the wrong nesting level, or receiving an input shape your code did not expect. Inspect a representative decoded record and its keys before deciding what the field should be called.
Recommended Free Tools
Choose a lookup pattern based on whether the field is optional
| Situation | Pattern | What it does |
|---|---|---|
| Optional field | mapping.get(key, fallback) |
Returns the value if present or the chosen fallback if absent; does not mutate a normal dictionary. |
| Required field | mapping[key] with explicit error handling |
Keeps missing required input detectable so the application can explain what is wrong. |
| Presence matters | if key in mapping: |
Lets you distinguish an absent key from a present key whose value is None. |
| Accumulating grouped data | defaultdict or setdefault() |
Initializes missing entries for a collection or other intended mutation. |
Optional fields: use get() with a deliberate fallback
For a field that can legitimately be absent, get() avoids a KeyError:
#1 Best Overall
salary = posting.get("salary", "Not listed")
The fallback should suit its use. None, an empty list, and a display string such as "Not listed" are different values. Choose one your downstream code can handle. A display string may work for a user interface but be inappropriate for calculations or data validation.
Required fields: report missing input instead of masking it
If the application requires a title or identifier, a fallback can hide a malformed record or make it look valid. Keep the failure explicit and translate it into a useful validation message when appropriate:
Rank #2
try:
title = posting["title"]
except KeyError as exc:
raise ValueError("Job posting is missing required field 'title'") from exc
This makes the input contract visible to whoever handles the record. An application might report the problem, reject the record, or route it for review; the right action depends on that application’s requirements.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Distinguish an absent key from a null value
posting.get("salary") returns None both when the key is absent and when it exists with a value of None. If those states mean different things, use membership testing or a unique sentinel:
_MISSING = object()
salary = posting.get("salary", _MISSING)
if salary is _MISSING:
print("salary key is absent")
elif salary is None:
print("salary key exists but has a null value")
A membership check is another clear option when you need to distinguish the cases:
if "salary" in posting:
salary = posting["salary"]
else:
salary = "Not listed"
Use defaultdict or setdefault only when mutation is intended
These tools are useful for building grouped results, but they are not interchangeable with a non-mutating optional-field lookup.
defaultdict for accumulating values
A defaultdict(list) can collect postings by category, while defaultdict(int) can count them. With bracket access, a missing key invokes the default factory and inserts the resulting value. For example:
from collections import defaultdict
postings_by_category = defaultdict(list)
postings_by_category["engineering"].append(posting)
By contrast, defaultdict.get() does not invoke the factory or insert a value. It behaves like normal dict.get() and returns None by default. The Python collections documentation describes these rules and grouping examples.
Best Value
setdefault when adding a default to the dictionary is desired
setdefault() returns an existing value or adds and returns the supplied default if the key is absent. Use it when that mutation is part of the design:
postings_by_category = {}
postings_by_category.setdefault("engineering", []).append(posting)
The dictionary changes when the default is added. The official collections documentation also shows setdefault() as a grouping alternative.
Check nested JSON objects one layer at a time
get() only looks up a key on the mapping it is called on. It does not guarantee that a nested object exists or is itself a dictionary. If a record is expected to contain a nested structure, validate each layer before looking up its child:
Free tools Windows power users keep installed
One-click scans. No signup required.
details = posting.get("details")
if not isinstance(details, dict):
raise ValueError("Job posting is missing a valid 'details' object")
location = details.get("location", "Not listed")
First check the decoded object's type and shape; do not assume a particular job-board response or a universal set of fields.
Quick debugging checklist
- Read the key named in the
KeyErrorand compare it with the keys actually present. - Check spelling and capitalization.
- Confirm that you are looking at the correct nesting level.
- Check whether the decoded input is a mapping and whether nested values have the expected type.
- Decide whether the field is optional or required before choosing a fallback.
- When absence differs from a present
None, use a membership test or sentinel.
The Python references for mapping operations and defaultdict document the relevant behavior.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

