Learn How To Fetch Data From A Python Dictionary
When you fetch a key with square brackets like data["naem"] and it does not exist, Python raises a KeyError. Here is how to fetch values safely, handle missing keys, and use every built-in dict method.
Python
data = {"name": "gagan", "sub": "cs"}
# 1. Direct indexing (raises KeyError if key is missing)
print(data["name"]) # gagan
# print(data["naem"]) # KeyError: 'naem'
# 2. Safe lookup with .get() (returns None or a custom default)
print(data.get("naem")) # None
print(data.get("naem", "Not found")) # Not found
# 3. Check membership first with 'in'
if "naem" in data:
print(data["naem"])
else:
print("Key 'naem' does not exist")
# 4. Catch KeyError with try / except
try:
print(data["naem"])
except KeyError:
print("Handled KeyError: 'naem' is missing")
# 5. Fetch value if present, or insert & return a default with .setdefault()
age = data.setdefault("age", 20)
print(age) # 20
print(data) # {'name': 'gagan', 'sub': 'cs', 'age': 20}
Here are all standard methods on a dict object with examples:
Python
d = {"name": "gagan", "sub": "cs"}
# keys() - returns a view of all keys
print(list(d.keys())) # ['name', 'sub']
# values() - returns a view of all values
print(list(d.values())) # ['gagan', 'cs']
# items() - returns a view of (key, value) tuples
print(list(d.items())) # [('name', 'gagan'), ('sub', 'cs')]
# get(key, default=None) - safe fetch without KeyError
print(d.get("sub")) # 'cs'
print(d.get("city", "N/A")) # 'N/A'
# setdefault(key, default=None) - gets value if key exists, else sets & returns default
print(d.setdefault("sub", "math")) # 'cs' (unchanged)
print(d.setdefault("level", "UG")) # 'UG' (added to d)
# update(other) - merges another dict or iterable of pairs (overwrites existing keys)
d.update({"sub": "it", "year": 2})
print(d) # {'name': 'gagan', 'sub': 'it', 'level': 'UG', 'year': 2}
# pop(key[, default]) - removes key and returns its value (default avoids KeyError)
removed = d.pop("year", None)
print(removed) # 2
print(d.pop("missing", "fallback")) # 'fallback'
# popitem() - removes and returns the last inserted (key, value) pair (raises KeyError if empty)
last_item = d.popitem()
print(last_item) # ('level', 'UG')
# copy() - returns a shallow copy of the dictionary
d_copy = d.copy()
print(d_copy) # {'name': 'gagan', 'sub': 'it'}
# fromkeys(iterable, value=None) - creates a new dict from keys with a shared value
new_d = dict.fromkeys(["a", "b", "c"], 0)
print(new_d) # {'a': 0, 'b': 0, 'c': 0}
# clear() - removes all items from the dictionary in place
d_copy.clear()
print(d_copy) # {}
Learn how to fetch data from a Python dictionary safely using .get(), .setdefault(), in, and try-except to prevent KeyError, along with complete examples of all
Shopeze.in
Boost via Reels & Images
Learn Python By Gagan Khanna
Professional Help for Growth
Key:value Pair In Python Dict Get Values From Dict Gagan Khanna Learn Python Python Dictionary Python Keyerror Python Dict Get Method Python Dictionary Methods Fetch Data From Dictionary Python Python Setdefault Cbse Python Class 11 Cbse Informatics Practices Python Programming Teachlive