Python Nested Data Structures
In this page:
nested = [[item1, item2], [item3, item4]]
nested[outer_index][inner_index]
List of Lists
List of lists 2D grid या matrix को represent करने का Python का standard तरीका है, जहाँ outer list rows रखती है और हर inner list उस row के columns रखती है — grid[row][column] उस position का element पढ़ता है, पहले outer list में index करके, फिर inner में।
उदाहरण: List of Lists
grid = [[1, 2], [3, 4]]
print(grid[1][0])
Dictionary of Dictionaries
किसी dictionary के अंदर dictionaries nest करने से आप related records को एक ही parent key के नीचे group कर सकते हैं, जैसे users[alice] = {age: 30, email: '...'} — यह उसी तरह है जैसे JSON APIs आमतौर पर profile या configuration data structure करते हैं।
उदाहरण: Dictionary of Dictionaries
users = {"alice": {"age": 30, "email": "[email protected]"}}
print(users["alice"]["age"])
List of Dictionaries
List of dictionaries — [{id: 1, name: A}, {id: 2, name: B}] — बिल्कुल वही shape है जो ज़्यादातर database query results और JSON API responses लेते हैं, जिसमें हर dict एक row या record represent करती है और list पूरे result set को।
उदाहरण: List of Dictionaries
records = [{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]
print(records[1]["name"])
Dictionary of Lists
एक single key को values की list से map करना (dict of lists) data को category के हिसाब से group करने के लिए natural structure है, जैसे tags_to_articles[python] = [article1, article2] जिसमें python tag वाला हर article एक key के नीचे होता है।
उदाहरण: Dictionary of Lists
tags_to_articles = {"python": ["article1", "article2"]}
print(tags_to_articles["python"])
Nested Data पर Iterate करना
Nested structures में घूमने का मतलब आमतौर पर nesting के हर level के लिए एक loop होता है — outer list पर एक for loop, उसके अंदर एक nested for loop (या dict iteration) — और हर level पर loop variable names सही रखना ही code को पठनीय बनाए रखता है।
उदाहरण: Iterating through Nested Data
grid = [[1, 2], [3, 4]]
for row in grid: # outer loop over each row
for value in row: # inner loop over each value in that row
print(value)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: