Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a dot "." to access members of dictionary?

How do I make Python dictionary members accessible via a dot "."?

For example, instead of writing mydict['val'], I'd like to write mydict.val.

Also I'd like to access nested dicts this way. For example

mydict.mydict2.val  

would refer to

mydict = { 'mydict2': { 'val': ... } } 
like image 242
bodacydo Avatar asked Feb 28 '10 18:02

bodacydo


People also ask

Can I access Python dictionary with dot?

We can create our own class to use the dot syntax to access a dictionary's keys.

How do you use the dot operator in Python?

Every object has certain attributes and methods. The connection between the attributes or the methods with the object is indicated by a “dot” (”.”) written between them. For example if dog is a class, then a dog named Fido would be its instance/object.


2 Answers

I've always kept this around in a util file. You can use it as a mixin on your own classes too.

class dotdict(dict):     """dot.notation access to dictionary attributes"""     __getattr__ = dict.get     __setattr__ = dict.__setitem__     __delattr__ = dict.__delitem__  mydict = {'val':'it works'} nested_dict = {'val':'nested works too'} mydict = dotdict(mydict) mydict.val # 'it works'  mydict.nested = dotdict(nested_dict) mydict.nested.val # 'nested works too' 
like image 63
derek73 Avatar answered Sep 19 '22 22:09

derek73


You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope to help you:

class Map(dict):     """     Example:     m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])     """     def __init__(self, *args, **kwargs):         super(Map, self).__init__(*args, **kwargs)         for arg in args:             if isinstance(arg, dict):                 for k, v in arg.iteritems():                     self[k] = v          if kwargs:             for k, v in kwargs.iteritems():                 self[k] = v      def __getattr__(self, attr):         return self.get(attr)      def __setattr__(self, key, value):         self.__setitem__(key, value)      def __setitem__(self, key, value):         super(Map, self).__setitem__(key, value)         self.__dict__.update({key: value})      def __delattr__(self, item):         self.__delitem__(item)      def __delitem__(self, key):         super(Map, self).__delitem__(key)         del self.__dict__[key] 

Usage examples:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) # Add new key m.new_key = 'Hello world!' # Or m['new_key'] = 'Hello world!' print m.new_key print m['new_key'] # Update values m.new_key = 'Yay!' # Or m['new_key'] = 'Yay!' # Delete key del m.new_key # Or del m['new_key'] 
like image 45
epool Avatar answered Sep 22 '22 22:09

epool