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

Python Nested Data Structures

Nested data एक ऐसा collection है जिसमें दूसरे collections रखे होते हैं, जैसे drawers के अंदर folders वाली एक filing cabinet। अंदर की चीज़ों तक पहुँचने के लिए आप हर level को बारी-बारी खोलते हैं।
Syntax
python
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

python
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

python
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

python
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

python
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

python
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)
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.