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

Dictionary: creating, adding, accessing, removing elements; methods (get(), pop(), popitem(), clear(), copy()) · Programming Skills · Gri-Learn