SoftwareSideHustles
How-To

How to Check if a Key Exists in a Dictionary, Object or Map

The right way to test for a key in Python dictionaries, JavaScript objects and Maps, Java maps, Go maps and C# dictionaries — and the falsy-value and prototype bugs in the wrong ways.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: Python if key in d:, JavaScript Object.hasOwn(obj, key) (or map.has(key) for a Map), Java map.containsKey(key), Go v, ok := m[key], C# dict.TryGetValue(key, out var v). If you also want the value with a fallback, use Python d.get(key, default), JavaScript obj[key] ?? fallback, or Java map.getOrDefault(key, fallback).

Key checks by language

LanguageExists?Get with defaultMissing key access
Pythonkey in dd.get(key, default)d[key] raises KeyError
JavaScript objectObject.hasOwn(obj, key)obj[key] ?? defaultreturns undefined
JavaScript Mapmap.has(key)map.get(key) ?? defaultreturns undefined
Javamap.containsKey(key)map.getOrDefault(key, d)get returns null
Go_, ok := m[key]v, ok := m[key]returns the zero value
C#dict.ContainsKey(key)dict.GetValueOrDefault(key, d)indexer throws KeyNotFoundException

How do I check if a key exists in a Python dictionary?

python
user = {"name": "Ada", "age": 0, "email": None}
"name" in user # True
"phone" in user # False
user.get("phone") # None
user.get("phone", "n/a") # 'n/a'

Use in — not in user.keys() (which works but adds nothing) and not has_key, which was removed in Python 3.

The falsy-value bug

python
if user.get("age"): # False — but the key exists, with value 0
...

0, "", [], False and None are all falsy. A check written as if d.get(k) treats "present but zero" exactly like "missing". This is a real source of bugs: a discount of 0%, an empty username or a count of zero gets ignored. When you mean "does the key exist?", write if "age" in user:. When you mean "is the value not None?", write if user.get("age") is not None:.

Ask forgiveness or permission?

python
try:
age = user["age"]
except KeyError:
age = None

Python style often prefers try/except (EAFP) when the key is usually present, and in or get when it is often missing. Both are fine; pick the one that reads clearly.

For counting and grouping, skip the check entirely with collections.defaultdict or Counter:

python
from collections import defaultdict
groups = defaultdict(list)
for order in orders:
groups[order.customer_id].append(order) # no KeyError, no check

How do I check if a key exists in a JavaScript object?

javascript
const user = { name: "Ada", age: 0, email: undefined };
Object.hasOwn(user, "age"); // true (ES2022)
"age" in user; // true
user.age !== undefined; // true
user.email !== undefined; // false — but the key exists!
"toString" in user; // true — inherited from Object.prototype
Object.hasOwn(user, "toString");// false
  • Object.hasOwn checks only the object's own keys. It replaces the older obj.hasOwnProperty(key), which breaks on objects created with Object.create(null) or that define their own hasOwnProperty.
  • in also finds inherited properties, which matters when keys come from user input — "constructor" in {} is true.
  • Comparing with undefined cannot tell "missing" from "present with value undefined".

For lookups keyed by arbitrary strings (user IDs, words), prefer a Map. It has a clear has method and no inherited keys.

Default values: ?? versus ||

javascript
const pageSize = options.pageSize || 20; // 0 becomes 20 — usually a bug
const pageSize2 = options.pageSize ?? 20; // only null/undefined become 20

The same falsy-value bug as Python, with the same fix: use ?? (nullish coalescing) when zero or empty string are valid values. Optional chaining (user.address?.city) avoids the TypeError when an intermediate object is missing — see Cannot read properties of undefined.

How do I check if a key exists in a Java Map?

java
Map<String, Integer> stock = new HashMap<>();
stock.put("apples", 0);
stock.put("pears", null);
stock.containsKey("pears"); // true
stock.get("pears"); // null — present, value null
stock.get("plums"); // null — missing
stock.getOrDefault("plums", 0); // 0
stock.getOrDefault("pears", 0); // null — the key exists, so its null value is returned

get returning null is ambiguous when null values are allowed, so use containsKey, or avoid storing nulls at all. Unboxing a null Integer into an int throws NullPointerException — a common crash with int count = map.get(key);.

For "insert if absent", use computeIfAbsent or merge:

java
Map<String, List<Order>> byCustomer = new HashMap<>();
byCustomer.computeIfAbsent(order.customerId(), k -> new ArrayList<>()).add(order);
counts.merge(word, 1, Integer::sum);

Go and C#

go
age, ok := ages["ada"]
if !ok {
// key missing; age is 0, the zero value
}

In Go, reading a missing key returns the zero value with no error, so ages["nobody"] is 0. The two-value "comma ok" form is the only way to tell a missing key from a stored zero.

csharp
if (ages.TryGetValue("ada", out var age)) { /* use age */ }

TryGetValue does one lookup instead of the two that ContainsKey followed by the indexer would.

Frequently asked questions

Is key in dict fast?

Yes — O(1) on average, because dictionaries are hash tables. key in list is O(n). See Big O notation explained.

How do I check for a nested key?

Python: d.get("a", {}).get("b"). JavaScript: obj?.a?.b !== undefined. For deeply nested optional data, validate the shape once at the boundary with a schema instead of checking at every access.

How do I check if a value (not a key) exists?

Python value in d.values(), JavaScript Object.values(obj).includes(value), Java map.containsValue(value). These are O(n).

Where this skill pays off

"Check whether a dictionary key exists" is one of the exercises in our preference labelling lab: two answers that are both correct, where the better one is chosen on clarity and the falsy-value trap. Making that kind of fine-grained judgement is the core of paid AI preference-ranking work — see how preference ranking works.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy