Last active
August 29, 2015 13:58
-
-
Save RussellLuo/9988008 to your computer and use it in GitHub Desktop.
A simple function for converting dict to dotted-dict.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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