Last active
June 4, 2017 02:16
-
-
Save impredicative/571be4f544201268bf61f35171b956c9 to your computer and use it in GitHub Desktop.
dict utils
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
import json | |
def pprint(obj): | |
print(json.dumps(obj, indent=2, sort_keys=True, default=str)) | |
def nested_dict_recursive_with_single_key(nested_key, value): | |
head, _sep, tail = nested_key.partition('.') | |
return {head: (nested_dict_recursive_with_single_key(tail, value) if tail else value)} | |
def nested_dict_iterative_with_single_key(nested_key, value): | |
data_dict = cur_dict = {} | |
for key in nested_key.split('.'): | |
prev_dict = cur_dict | |
cur_dict = cur_dict.setdefault(key, {}) | |
prev_dict[key] = value # pylint: disable=undefined-loop-variable | |
return data_dict | |
def nested_dict(**nested_items): | |
"""Return a dictionary created from dot-separated arbitrarily nested keys and their values. | |
Example: | |
>>> nested_dict(**{'a': 1, 'b.c': 2, 'd.e.f': 3, 'd.e.g': 4}) | |
{'b': {'c': 2}, 'a': 1, 'd': {'e': {'f': 3, 'g': 4}}} | |
""" | |
data_dict = cur_dict = {} | |
for nested_key, val in nested_items.items(): | |
for key in nested_key.split('.'): | |
prev_dict = cur_dict | |
cur_dict = cur_dict.setdefault(key, {}) | |
prev_dict[key] = val | |
cur_dict = data_dict | |
return data_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment