← Back to Python Course | Chapter 6: Data Structures | Lesson 6 of 12

Python Dictionaries

Dictionary एक असली dictionary या phone book जैसी है: आप किसी नाम (key) से कुछ ढूँढते हैं और उसकी जानकारी (value) पाते हैं। यह labeled facts को साथ रखने के लिए बढ़िया है।
Syntax
python
dict_name = {key1: value1, key2: value2}
dict_name[key]

Dictionary क्या है?

Dictionary unique, immutable keys (strings, numbers, या tuples) को values से map करती है, और Python 3.7 से iterate करते समय insertion order बना रहता है।

यह उस हर चीज़ के लिए natural structure है जिसे आप otherwise एक lookup table के रूप में model करते, जैसे username-to-user-record mapping।

उदाहरण: What is a Dictionary?

python
user = {"name": "Alex", "age": 30}
print(user)

Values को Access और Modify करना

my_dict[key] पढ़ने पर key न मिलने पर KeyError raise होता है, जबकि my_dict[key] = value लिखने पर यह किसी मौजूदा entry को update करता है या नई बनाता है — कोई अलग insert operation नहीं है, assignment दोनों situations को संभाल लेता है।

उदाहरण: Accessing and Modifying Values

python
user = {"name": "Alex"}
print(user["name"])  # raises KeyError if "name" were missing
user["name"] = "Sam"  # updates the existing key
print(user)

Items जोड़ना और हटाना

किसी नई key को assign करने पर वह dictionary में जुड़ जाती है; del my_dict[key] एक entry हटाता है और न मिलने पर KeyError raise करता है, इसलिए पहले key in my_dict check करना (या .pop(key, None) इस्तेमाल करना) missing keys पर crash होने से बचाता है।

उदाहरण: Adding and Deleting Items

python
user = {"name": "Alex"}
user["age"] = 30  # adds a new key
del user["age"]  # removes it
print(user)

Dictionary पर Iterate करना

Dictionary को सीधे iterate करना (for k in my_dict) keys देता है; .values() सिर्फ values देता है और .items() (key, value) pairs देता है, जो लूप में दोनों चाहिए होने पर सबसे common form है।

उदाहरण: Iterating Through a Dictionary

python
user = {"name": "Alex", "age": 30}
for key, value in user.items():  # yields both key and value together
    print(key, value)

Dictionary Length और Duplicate Keys

Dictionary keys स्वाभाविक रूप से unique होती हैं — किसी मौजूदा key को assign करने पर duplicate entry बनने की बजाय उसकी value overwrite हो जाती है — और len(my_dict) keys और values को अलग-अलग नहीं, key-value pairs की गिनती करता है।

उदाहरण: Dictionary Length and Duplicate Keys

python
user = {"name": "Alex"}
user["name"] = "Sam"  # overwrites, not a duplicate
print(user)
print(len(user))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.