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

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


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'


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 keym.new_key = 'Hello world!'# Orm['new_key'] = 'Hello world!'print m.new_keyprint m['new_key']# Update valuesm.new_key = 'Yay!'# Orm['new_key'] = 'Yay!'# Delete keydel m.new_key# Ordel m['new_key']


Install dotmap via pip

pip install dotmap

It does everything you want it to do and subclasses dict, so it operates like a normal dictionary:

from dotmap import DotMapm = DotMap()m.hello = 'world'm.hellom.hello += '!'# m.hello and m['hello'] now both return 'world!'m.val = 5m.val2 = 'Sam'

On top of that, you can convert it to and from dict objects:

d = m.toDict()m = DotMap(d) # automatic conversion in constructor

This means that if something you want to access is already in dict form, you can turn it into a DotMap for easy access:

import jsonjsonDict = json.loads(text)data = DotMap(jsonDict)print data.location.city

Finally, it automatically creates new child DotMap instances so you can do things like this:

m = DotMap()m.people.steve.age = 31

Comparison to Bunch

Full disclosure: I am the creator of the DotMap. I created it because Bunch was missing these features

  • remembering the order items are added and iterating in that order
  • automatic child DotMap creation, which saves time and makes for cleaner code when you have a lot of hierarchy
  • constructing from a dict and recursively converting all child dict instances to DotMap