Python Nested Dictionaries
In this page:
nested_dict = {
key1: {inner_key: value},
key2: {inner_key: value}
}
nested_dict[key1][inner_key]
Nested Dictionary बनाना
Nested dictionary बिल्कुल एक regular dictionary literal की तरह लिखी जाती है, बस इसकी एक या ज़्यादा values खुद dictionary literals होती हैं — {"sam": {"age": 28, "city": "Austin"}} एक outer dictionary के अंदर, username से keyed, एक level nested single user का data represent करता है।
उदाहरण: Creating a Nested Dictionary
data = {"sam": {"age": 28, "city": "Austin"}}
print(data)
Nested Values को Access करना
किसी deeply nested value तक पहुँचने का मतलब है एक-एक करके square-bracket lookups chain करना — data["users"]["sam"]["address"]["city"] नेस्टिंग के तीन levels से गुज़रकर, structure में nested होने के ठीक उसी क्रम में, final value तक पहुँचता है।
उदाहरण: Accessing Nested Values
data = {"users": {"sam": {"address": {"city": "Austin"}}}}
print(data["users"]["sam"]["address"]["city"])
Nested Dictionary Values को Modify करना
Nested dictionary के अंदर किसी value को update करना उसे पढ़ने वाला ही chained bracket syntax इस्तेमाल करता है — data["users"]["sam"]["age"] = 29 nested structure के अंदर जाकर सिर्फ उस एक specific value को update करता है, बाकी structure को बिना छुए छोड़ देता है।
उदाहरण: Modifying Nested Dictionary Values
data = {"users": {"sam": {"age": 28}}}
data["users"]["sam"]["age"] = 29 # chained brackets reach into the nested dict
print(data)
Nested Dictionary पर Loop करना
Nested dictionary पर loop करने का मतलब आमतौर पर top-level keys पर एक outer loop होता है, जिसके अंदर एक inner loop (या direct access) हर nested dictionary की अपनी keys और values को handle करता है — जिससे आप हर टुकड़े hierarchical data को व्यवस्थित रूप से process कर सकें।
उदाहरण: Looping Over a Nested Dictionary
users = {"sam": {"age": 28}, "alex": {"age": 30}}
for name, info in users.items(): # outer loop over each user
print(name, info["age"]) # info is the nested dict for that user
Nested Dictionaries में Shallow Copy का Trap
.copy() (या dict()) से किसी outer dictionary को copy करने पर सिर्फ top level copy होता है — इसके अंदर की कोई भी nested dictionary original और copy के बीच shared reference रहती है, यानी copy के through nested value में बदलाव original को भी असर करता है। genuinely independent copy के लिए copy.deepcopy() चाहिए।
उदाहरण: The Shallow Copy Trap with Nested Dictionaries
import copy
original = {"user": {"age": 28}}
shallow = original.copy()
shallow["user"]["age"] = 99
print(original["user"]["age"]) # also changed
deep = copy.deepcopy(original)
deep["user"]["age"] = 1
print(original["user"]["age"]) # unaffected
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: