Python Dictionaries
In this page:
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?
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
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
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
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
user = {"name": "Alex"}
user["name"] = "Sam" # overwrites, not a duplicate
print(user)
print(len(user))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: