Maison > Article > développement back-end > Pouvez-vous accéder aux membres du dictionnaire à l’aide de la notation par points en Python ?
Dot Notation for Dictionary Access: Extending Python's Dictionary Class
In Python, accessing dictionary members typically requires the bracket notation, such as mydict['key']. However, it is possible to use dot notation for the same purpose, making it more convenient and readable. This can be particularly useful for accessing nested dictionaries.
One way to achieve this is by implementing a custom class that extends the built-in dict class. The dotdict class presented here:
class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
To use the dotdict class:
mydict = {'val': 'it works'} nested_dict = {'val': 'nested works too'} mydict = dotdict(mydict)
Now, you can access dictionary members using dot notation:
mydict.val # 'it works'
You can even access nested dictionaries in the same way:
mydict.nested = dotdict(nested_dict) mydict.nested.val # 'nested works too'
This method provides a convenient and intuitive way to interact with dictionaries, especially when dealing with deeply nested structures.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!