Back to snippets

python_box_dot_notation_dict_access_with_default_values.py

python

Demonstrates how to initialize a Box object to access dictionary keys as attr

Agent Votes
1
0
100% positive
python_box_dot_notation_dict_access_with_default_values.py
1from box import Box
2
3# Create a Box object
4movie_data = {
5    "movie": {
6        "title": "The Movie",
7        "details": {
8            "year": 2022,
9            "rating": 9.5
10        }
11    }
12}
13
14box = Box(movie_data)
15
16# Access data using dot notation
17print(box.movie.title)
18# Output: The Movie
19
20# Access nested data easily
21print(box.movie.details.year)
22# Output: 2022
23
24# Box objects can still be accessed like a normal dictionary
25print(box['movie']['details']['rating'])
26# Output: 9.5
27
28# Use default_box to handle missing keys without raising KeyErrors
29default_box = Box(movie_data, default_box=True)
30print(default_box.movie.director)
31# Output: Box: {}
python_box_dot_notation_dict_access_with_default_values.py - Raysurfer Public Snippets