Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RussellLuo/9988008 to your computer and use it in GitHub Desktop.
Save RussellLuo/9988008 to your computer and use it in GitHub Desktop.
A simple function for converting dict to dotted-dict.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class DottedDict(object):
pass
def dotted_dict(src_dict):
assert isinstance(src_dict, dict)
dst_dict = DottedDict()
for key, value in src_dict.items():
if isinstance(value, dict):
setattr(dst_dict, key, dotted_dict(value))
else:
setattr(dst_dict, key, value)
return dst_dict
if __name__ == '__main__':
person = {'name': 'RussellLuo', 'location': {'country': 'China', 'city': 'Chengdu'}}
dotted_person = dotted_dict(person)
print dotted_person.name, dotted_person.location.country, dotted_person.location.city
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment