Dictionary: creating, adding, accessing, removing elements; methods (get(), pop(), popitem(), clear(), copy())

Python dictionaries क्रमिक numeric indexing को label-based lookup से बदलते हैं, आपको distinct keys के ज़रिए data values तुरंत retrieve करने देते हुए।

11 min read · 12 cards · 3 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Index Numbers से मुक्त होना

आपके Semester 1 BCA104 C labs में, अगर आप track करना चाहते कि आपने 'food', 'travel', या 'laundry' जैसी अलग categories पर कितना पैसा ख़र्च किया, आपको दो अलग arrays बनाए रखने या जटिल search loops वाली एक custom structure बनानी पड़ती। अगर आप food expense देखना चाहते, आपको एक string array में loop करना, match index खोजना, और उसी index number को एक अलग numeric array पर इस्तेमाल करना पड़ता। Python इस भद्दे संरचनात्मक matching को क्यों छोड़ देता है, आपको values को सीधे सार्थक textual labels से link करने देते हुए?

Theory

College Locker Room

एक list या एक array को 0, 1, 2, और 3 numbered एक जैसी benches की एक लंबी line की तरह सोचिए। एक item खोजने के लिए, आपको इसकी बिल्कुल bench position जाननी होगी। एक Python dictionary, हालाँकि, college campus lockers की एक दीवार की तरह है। हर locker अपने sequence number की परवाह नहीं करता; बजाय इसके, इसके दरवाज़े पर 'Samosa', 'Chai', या 'Bus' जैसा एक distinct painted name label होता है। आप 'item 2 दो' कहकर एक expense नहीं देखते; आप बस 'Samosa' labeled दरवाज़े तक चलते हैं, key घुमाते हैं, और अंदर store price बाहर निकालते हैं।

Theory

Dictionary की संरचना औपचारिक रूप से

Python में एक dictionary curly braces {} में लपेटे associative key-value pairs के रूप में store data elements का एक unordered, mutable collection है। हर entry key: value के रूप में map की जाती है, जहाँ keys अपने corresponding values access करने के लिए custom labels की तरह काम करती हैं। Dictionaries सख़्त key uniqueness लागू करते हैं: जबकि values जितनी चाहें duplicate हो सकती हैं, keys पूरी तरह unique और immutable data types (जैसे strings, integers, या tuples) होनी चाहिए। एक element access करना bracket syntax (dict[key]) या विशेष extraction methods इस्तेमाल करता है।

At a glance

Table 1: data lookup और element removal के लिए ज़रूरी Python dictionary methods।

Method ToolMemory पर की गई ActionKey-Missing Behavior
ledger.get(key, default)एक ख़ास key के लिए एक value सुरक्षित रूप से retrieve करता है।बिना crash किए default value (या None) return करता है।
ledger.pop(key)निर्दिष्ट key हटाता और इसकी value return करता है।एक default fallback न दिए जाने पर एक KeyError फेंकता है।
ledger.popitem()आख़िरी insert की गई key-value tuple हटाता और return करता है।एक empty dictionary पर call करने पर एक KeyError फेंकता है।
ledger.copy()dictionary की एक shallow clone copy बनाता है।memory में एक ताज़ा dictionary block बनाता है।
ledger.clear()dictionary के अंदर सारी key-value entries मिटाता है।पीछे एक empty dictionary object {} छोड़ता है।

Theory

Worked Example: Expense Hub बनाना

आइए देखें कि हमारा PocketMoney system एक dictionary structure इस्तेमाल करके category budgets कैसे track करता है। हम एक dictionary initialize करेंगे, नई tracking metrics जोड़ेंगे, safe get method दिखाएँगे, और एक item साफ़-सुथरे memory से बाहर pop करेंगे।

Practical

PocketMoney Dictionary Controller

# Step 1: Initializing a baseline expense ledger
expense_ledger = {"samosa": 30, "travel": 50}

# Step 2: Adding a new key-value pair dynamically
expense_ledger["stationery"] = 120

# Step 3: Overwriting an existing key value
expense_ledger["samosa"] = 35

# Step 4: Accessing values safely via get()
safe_fetch = expense_ledger.get("laundry", 0)

# Step 5: Popping a key-value entry out completely
travel_cost = expense_ledger.pop("travel")

print("Final Ledger State:", expense_ledger)
print("Safe Fetch (laundry):", safe_fetch)
print("Popped Travel Cost:", travel_cost)

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

Ledger Mutations को ट्रेस करें

ऊपर के Python tracking script का विश्लेषण कीजिए। screen पर print होने पर expense_ledger के अंदर कौन से बिल्कुल mappings बचेंगे? math और keys ध्यान से हल कीजिए।

Show the answer

script output करेगी:

Final Ledger State: {'samosa': 35, 'stationery': 120}

Safe Fetch (laundry): 0

Popped Travel Cost: 50

क्यों? इसे ट्रेस करते हैं: Base dictionary {'samosa': 30, 'travel': 50} है। 'stationery' जोड़ना इसे फैलाता है। 'samosa' overwrite करना इसकी value 30 से 35 में बदलता है। expense_ledger.get('laundry', 0) कोई 'laundry' key नहीं पाता, तो यह बिना crash किए fallback value 0 return करता है। आख़िर में, pop('travel') 50 निकालता है और 'travel' key पूरी तरह हटाता है, पीछे दो pairs छोड़ते हुए।

Quiz

क्या होता है अगर एक programmer standard bracket notation, जैसे print(expense_ledger["entertainment"]), इस्तेमाल करके एक ग़ायब key access करने की कोशिश करता है, जब वह key मौजूद नहीं?

  1. यह अपने-आप None return करता है।
  2. यह एक blank string "" print करता है।
  3. यह एक KeyError फेंकता है और program crash करता है।
  4. यह key को 0 की एक default value के साथ append करता है।
Show the answer

यह एक KeyError फेंकता है और program crash करता है।

dict[key] जैसा सीधा bracket notation इस्तेमाल करना Python को उस key cell को तुरंत खोजने पर मजबूर करता है। अगर key collection के अंदर मौजूद नहीं, interpreter execution रोकता है और एक KeyError exception फेंकता है। इस crash से बचने के लिए, इसके बजाय .get() method इस्तेमाल कीजिए!

Quiz

इस declaration पर विचार कीजिए: data = {"ID": 101, "ID": 202}। एक script के अंदर compile होने पर data["ID"] की value क्या होगी?

  1. 101
  2. 202
  3. [101, 202] रखता एक list array
  4. यह एक SyntaxError फेंकता है क्योंकि duplicate keys स्पष्ट रूप से प्रतिबंधित हैं।
Show the answer

202

Python dictionary keys पूरी तरह unique होनी चाहिए। अगर आप duplicate keys के साथ एक dictionary declare करते हैं, Python एक compile error नहीं फेंकता; बजाय इसके, यह बाएँ से दाएँ पढ़ता है, और अंतिम value सारी पिछली को overwrite करती है। इस तरह, key "ID" नवीनतम value लेती है, जो 202 है।

Watch out

Classic जाल: Missing Key Bracket Crash

university viva examinations में सबसे आम marks-गँवाने वाली ग़लती search queries के लिए bracket notation my_dict[key] इस्तेमाल करना है जहाँ key अनुपस्थित हो सकती है। External user files या गंदे inputs अक्सर missing keys रखते हैं। unpredictable datasets parse करते समय crash-proof programs बनाने के लिए हमेशा brackets के बजाय my_dict.get(key, fallback) इस्तेमाल कीजिए।

Theory

Dictionaries को Semester 3 से जोड़ना

Associative mapping संरचित internet data exchange layers की नींव है। Semester 3 (BCA303) में, जब आप एक Python web server application को एक external API से connect करते हैं या configuration profiles load करते हैं, data JSON (JavaScript Object Notation) के रूप में आएगा। Python JSON structures को natively nested dictionaries के रूप में पढ़ता है, आपको positional numbers के बजाय strings इस्तेमाल करके configurations देखने देते हुए।

Summary

Key takeaways

  • Dictionaries mutable collections हैं जो unique, immutable keys को सीधे data values पर map करते हैं।
  • Elements एक curly brace सीमा के अंदर colons से अलग किए key-value pairs के रूप में store होते हैं।
  • सीधे bracket lookups एक KeyError crash trigger करते हैं अगर माँगी key dictionary से अनुपस्थित हो।
  • get method values सुरक्षित रूप से निकालती है, key ग़ायब होने पर एक वैकल्पिक fallback value return करते हुए।
  • pop और popitem methods values निकालकर और pairs स्थायी रूप से delete करके dictionary mutate करती हैं।
  • Memory Hook: Brackets ग़ायब data पर crash होते हैं, get defaults सँभालता है, keys absolute रहती हैं!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python Collections

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati