Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P4.3 Python Dictionaries: Keys आणि Values सोप्या भाषेत

By Ravindra Bagale

हे का शिकायचं?

Product च्या नावावरून price शोधायची असेल तर index पेक्षा नाव (key) वापरणं सोपं.

हे काय आहे?

Dictionary म्हणजे { } मधल्या key: value जोड्या. d[key] value देतो, d.get(key, default) key नसेल तर error न देता default देतो.

कसं करायचं?

Step 1. {key: value} लिहा.

Step 2. d[key] ने वाचा.

Step 3. सुरक्षित वाचनासाठी get() वापरा.

Python आणि इतर भाषा: तुलना

या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.

भाषाCode
Pythonprices["milk"]
Javaprices.get("milk") (with a HashMap)
JavaScriptprices["milk"] (an object)
Goprices["milk"] (a map)

उदाहरणं: copy करा आणि चालवा

उदाहरण A: Price list

हा code चालवा:

prices = {"milk": 56, "bread": 40, "eggs": 84}
print(prices["milk"])

तुम्हाला दिसणारा output:

56

याचा अर्थ: Key म्हणजे product, value म्हणजे price.

उदाहरण B: जोडा, बदला आणि सुरक्षित वाचा

हा code चालवा:

prices = {"milk": 56, "bread": 40, "eggs": 84}
prices["bread"] = 45
prices["butter"] = 60
print(prices)
print(prices.get("jam", 0))

तुम्हाला दिसणारा output:

{'milk': 56, 'bread': 45, 'eggs': 84, 'butter': 60}
0

याचा अर्थ: नवीन key ला value दिली की ती जोडली जाते. get() ने missing key वर default मिळाला.

उदाहरण C: Customer record

हा code चालवा:

customer = {"id": "AC-77", "name": "Lukas", "balance": 5400.0, "currency": "CHF"}
print(customer["name"], customer["balance"], customer["currency"])
for key, value in customer.items():
    print(key, "->", value)

तुम्हाला दिसणारा output:

Lukas 5400.0 CHF
id -> AC-77
name -> Lukas
balance -> 5400.0
currency -> CHF

याचा अर्थ: एका customer ची सगळी माहिती एका dictionary मध्ये — हीच table ची एक row.