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
| Language | Exists? | Get with default | Missing key access |
|---|---|---|---|
| Python | key in d | d.get(key, default) | d[key] raises KeyError |
| JavaScript object | Object.hasOwn(obj, key) | obj[key] ?? default | returns undefined |
JavaScript Map | map.has(key) | map.get(key) ?? default | returns undefined |
| Java | map.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?
user = {"name": "Ada", "age": 0, "email": None}
"name" in user # True"phone" in user # Falseuser.get("phone") # Noneuser.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
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?
try: age = user["age"]except KeyError: age = NonePython 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:
from collections import defaultdictgroups = defaultdict(list)for order in orders: groups[order.customer_id].append(order) # no KeyError, no checkHow do I check if a key exists in a JavaScript object?
const user = { name: "Ada", age: 0, email: undefined };
Object.hasOwn(user, "age"); // true (ES2022)"age" in user; // trueuser.age !== undefined; // trueuser.email !== undefined; // false — but the key exists!"toString" in user; // true — inherited from Object.prototypeObject.hasOwn(user, "toString");// falseObject.hasOwnchecks only the object's own keys. It replaces the olderobj.hasOwnProperty(key), which breaks on objects created withObject.create(null)or that define their ownhasOwnProperty.inalso finds inherited properties, which matters when keys come from user input —"constructor" in {}istrue.- Comparing with
undefinedcannot tell "missing" from "present with valueundefined".
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 ||
const pageSize = options.pageSize || 20; // 0 becomes 20 — usually a bugconst pageSize2 = options.pageSize ?? 20; // only null/undefined become 20The 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?
Map<String, Integer> stock = new HashMap<>();stock.put("apples", 0);stock.put("pears", null);
stock.containsKey("pears"); // truestock.get("pears"); // null — present, value nullstock.get("plums"); // null — missingstock.getOrDefault("plums", 0); // 0stock.getOrDefault("pears", 0); // null — the key exists, so its null value is returnedget 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:
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#
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.
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.