nested object collection in python

In Python, we can create a nested object collection using dictionaries which allows us to store and access data in a hierarchical manner.

To create a dictionary that contains another dictionary as a value, we can do something like this:

main.py
nested_dict = {'outer_key': {'inner_key': 'value'}}
52 chars
2 lines

We can access the value of inner_key using the following syntax:

main.py
value = nested_dict['outer_key']['inner_key']
46 chars
2 lines

If we want to create a collection of nested objects, we can use a list of dictionaries. Here is an example:

main.py
nested_list = [
    {'name': 'Alice', 'age': 25, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA'}},
    {'name': 'Bob', 'age': 30, 'address': {'street': '456 Elm St', 'city': 'Othertown', 'state': 'NY'}}
]
228 chars
5 lines

We can access the data for each individual record using indexing:

main.py
alice_address = nested_list[0]['address']
bob_age = nested_list[1]['age']
74 chars
3 lines

This creates a powerful data structure for managing collections of related data.

gistlibby LogSnag