Python Dictionary Methods
In this page:
dict_name.get(key, default)
dict_name.keys()
dict_name.values()
dict_name.items()
dict_name.update(other_dict)
Keys, Values, और Items निकालना
keys(), values(), और items() static copies नहीं बल्कि live, dynamic views लौटाते हैं, यानी वे बाद में dictionary में हुए बदलावों को अपने-आप reflect करते हैं; items() का (key, value) tuples लौटाना ही 'for k, v in d.items()' को standard iteration pattern बनाता है।
उदाहरण: Retrieving Keys, Values, and Items
user = {"name": "Alex", "age": 30}
print(list(user.keys())) # just the keys
print(list(user.values())) # just the values
print(list(user.items())) # (key, value) tuples
get() से Safe Lookups
get(key, default) किसी key को बिना कभी KeyError raise किए लुकअप करता है — अगर key न मिले तो यह None (या आपका दिया default) लौटाता है, जो हर बार जब key का होना guaranteed न हो, square-bracket access से ज़्यादा safe है।
उदाहरण: Safe Lookups with get()
user = {"name": "Alex"}
print(user.get("age")) # missing key returns None instead of raising an error
print(user.get("age", 0)) # custom default when the key is missing
pop() से Items हटाना
pop(key) उस key को हटाकर उसकी value लौटा देता है (missing key पर KeyError रोकने के लिए optionally एक default के साथ), जबकि popitem() सबसे हाल ही insert हुए (key, value) pair को tuple के रूप में हटाकर लौटाता है — dict को stack की तरह treat करने में उपयोगी।
उदाहरण: Removing Items with pop()
user = {"name": "Alex", "age": 30}
age = user.pop("age") # removes "age" and returns its value
print(age, user)
Update करना और Merge करना
update() दूसरी dictionary या key-value pairs के किसी iterable को मौजूदा dictionary में in place merge करता है; matching keys नई values से overwrite हो जाती हैं जबकि मौजूदा dict की unmatched keys बिना छुए रहती हैं।
उदाहरण: Updating and Merging
user = {"name": "Alex", "age": 30}
user.update({"age": 31, "city": "NYC"}) # age is overwritten, city is added
print(user)
Default Values और Clearing
setdefault(key, default) अगर key मौजूद है तो उसकी existing value लौटाता है, या दिया गया default डालकर उसे लौटाता है — यह आम 'if key not in d: d[key] = default' pattern का एक compact एक-line replacement है। clear() पूरी dictionary को खाली कर देता है।
उदाहरण: Default Values and Clearing
user = {"name": "Alex"}
user.setdefault("age", 18) # inserts "age": 18 since the key is missing
print(user)
user.clear() # removes every key
print(user)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: