Skip to content

Instantly share code, notes, and snippets.

@impredicative
Last active June 4, 2017 02:16
Show Gist options
  • Save impredicative/571be4f544201268bf61f35171b956c9 to your computer and use it in GitHub Desktop.
Save impredicative/571be4f544201268bf61f35171b956c9 to your computer and use it in GitHub Desktop.
dict utils
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