Home › Hindi › KeyError का solution

Python KeyError का solution — Hindi में dictionary guide

🌐 यह page Hindi में है · Read this in English →

Exact message: KeyError: 'age'get() vs in vs try/exceptFree dictionary practice

KeyError का सीधा मतलब

Dictionary से आपने ऐसी key माँगी जो उसमें मौजूद नहीं है। सबसे अच्छी बात — error message में वही key छपती है जो आपने माँगी थी, तो आधा जवाब message में ही मिल जाता है।

student = {"naam": "Priya", "class": 10}
print(student["age"])

Traceback (most recent call last):
  File "main.py", line 2, in <module>
KeyError: 'age'

पहला काम हमेशा यही करो — crash से ठीक पहले यह line लगाओ और देखो कि dictionary में असल में है क्या:

print(list(student.keys()))   # ['naam', 'class']

कारण 1 — Spelling, case या छुपा हुआ space

Keys बिल्कुल exact match होती हैं। ये चारों अलग-अलग keys हैं: 'naam', 'Naam', 'NAAM', 'naam ' (आखिर में space)।

data = {"Naam": "Priya"}
print(data["naam"])    # ❌ KeyError: 'naam' — capital N चाहिए था

File या form से आया data अक्सर extra space लेकर आता है। इसलिए keys बनाते वक्त ही साफ कर लो:

data = {k.strip().lower(): v for k, v in raw.items()}

कारण 2 — Number और string वाली key को एक समझ लेना

marks = {1: "Pehla", 2: "Doosra"}
print(marks["1"])     # ❌ KeyError: '1' — यह string है, number 1 नहीं
print(marks[1])       # ✅ Pehla

JSON से data पढ़ने पर यह बहुत होता है — JSON में keys हमेशा strings होती हैं, इसलिए data["101"] चलेगा, data[101] नहीं।

Solution 1 — .get() से default value (सबसे आसान)

student = {"naam": "Priya"}

print(student.get("age"))        # None — crash नहीं
print(student.get("age", 0))     # 0 — अपना default
print(student.get("naam", "?"))  # Priya

कब use करें: जब key का न होना normal बात हो (optional field, जैसे "middle name")। कब न करें: जब key का होना ज़रूरी हो — तब crash होना ही सही है, वरना bug चुपचाप आगे बढ़ जाएगा और बाद में और अजीब जगह फटेगा।

Solution 2 — in से check, और setdefault से counting

if "age" in student:
    print(student["age"])
else:
    print("Age available nahi hai")

Counting वाले loops में KeyError बहुत आता है। तीन साफ तरीके:

counts = {}
for ch in "banana":
    counts[ch] = counts[ch] + 1     # ❌ KeyError पहली बार में

# ✅ तरीका 1: get with default
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1

# ✅ तरीका 2: setdefault
for ch in "banana":
    counts.setdefault(ch, 0)
    counts[ch] += 1

# ✅ तरीका 3: defaultdict
from collections import defaultdict
counts = defaultdict(int)
for ch in "banana":
    counts[ch] += 1

Solution 3 — try/except (सिर्फ जहाँ सच में ज़रूरत हो)

try:
    age = student["age"]
except KeyError:
    age = 0
    print("Age missing — default 0 laga diya")

ध्यान: except: अकेला मत लिखो और पूरे program को try में मत लपेटो — सिर्फ वही एक line लपेटो जिससे error आ सकता है, वरना असली bugs छुप जाएँगे।

Nested dictionary में KeyError

API और JSON data में सबसे ज़्यादा यहीं crash होता है, क्योंकि पूरी chain में कहीं भी एक key गायब हो सकती है।

data = {"user": {"naam": "Amit"}}
print(data["user"]["email"])          # ❌ KeyError: 'email'

print(data.get("user", {}).get("email", "N/A"))   # ✅ N/A

Chained .get() में हर level का default {} रखो — तभी अगला .get() भी safe रहता है।

Key delete करते वक्त भी KeyError आता है

del student["age"]         # ❌ KeyError अगर key नहीं है
student.pop("age")         # ❌ यही हाल
student.pop("age", None)   # ✅ default दे दो, crash नहीं होगा

🛠️ Practice करो (free, browser में)

पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।

सारे free problems देखो →

अक्सर पूछे जाने वाले सवाल

Python में KeyError क्यों आता है?

जब आप dictionary से ऐसी key माँगते हैं जो उसमें मौजूद नहीं है। error message में वही key लिखी होती है जो missing है, इसलिए सबसे पहले print(list(d.keys())) से मौजूद keys देख लें।

KeyError से कैसे बचें?

optional keys के लिए d.get("key", default) इस्तेमाल करें, condition के लिए if "key" in d लिखें, counting के लिए get(k, 0) + 1 या collections.defaultdict, और delete करते समय d.pop("key", None)।

d["key"] और d.get("key") में क्या फर्क है?

d["key"] key न मिलने पर KeyError देकर program रोक देता है, जबकि d.get("key") चुपचाप None (या आपका दिया हुआ default) लौटाता है। ज़रूरी keys के लिए [] रखें ताकि bug छुपे नहीं।

JSON data में KeyError क्यों आता है जबकि key दिख रही है?

अक्सर type का फर्क होता है — JSON में keys हमेशा strings होती हैं, इसलिए data[101] fail होगा पर data["101"] चलेगा। कभी-कभी key में extra space भी होता है, इसे .strip() से साफ करें।

आगे पढ़ो