Python की मूल बातें
Merge Dictionaries in Python with | and update()
Combine default settings with user choices in one expression, and see which value wins when keys clash.
आप क्या सीखेंगे
- Merging with the | operator (Python 3.9+)
- Updating in place with |= and update()
- Which value wins for duplicate keys
defaults | preferences
defaults
- theme: dark
- language: en
preferences
- language: vi
- font_size: 16
result
- theme: dark
- language: vi (from preferences)
- font_size: 16
The right side wins
Merge करते समय तय करना होता है कि key conflict पर कौन-सा value रखा जाए।
मुख्य बातें
- defaults | preferences creates a new dictionary with both sets of keys.
- For a key in both, the value from the right side is kept.
- defaults |= preferences or
defaults.update(preferences)changes defaults in place. - {**a, **b} does the same in older Python versions.
इसका उपयोग कब करें?
- चलने योग्य code से Python syntax सीखें।
- बड़ी programming समस्याओं से पहले मजबूत आधार बनाएँ।
- स्थानीय setup के बिना किसी विचार को तुरंत जाँचें।
देखें यह कैसे काम करता है
एक key लिखें और उसे सहेजें या खोजें। Python key को हैश करके उसकी जगह सीधे ढूँढ लेता है, हर एंट्री देखने की ज़रूरत नहीं पड़ती।
उदाहरण कोड
main.py
defaults = {"theme": "dark", "language": "en"}
preferences = {"language": "vi", "font_size": 16}
settings = defaults | preferences
print(settings)
अपेक्षित आउटपुट
{'theme': 'dark', 'language': 'vi', 'font_size': 16}
यह कैसे काम करता है
Merge operator नई dictionary बनाता है; दाईं ओर का value समान बाईं key को overwrite करता है।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- Code चलाने से पहले output का अनुमान लगाएँ।
- खाली और गलत input संभालें।
- Logic को function में रखें और tests जोड़ें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज