Created
May 19, 2019 17:00
-
-
Save NoFishLikeIan/1e460dfa427778b5ccadf9608d60decd to your computer and use it in GitHub Desktop.
Two utils functions to generate iterative settable dicts.
This file contains 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
from typing import List | |
from collections import defaultdict | |
def nested_set(nested_dict: defaultdict, path: List[str]) -> defaultdict: | |
''' | |
A function that sets a value to a defaultdict given a path of keys. | |
Example: | |
d = defaultdict(dict) | |
d = nested_set(d, ['hello', 'ciao', 3]) | |
print(d) | |
>>> { 'hello' : { 'ciao' : 3 } } | |
''' | |
[key, *rest] = path | |
if len(rest) == 1: | |
nested_dict[key] = rest[0] | |
return nested_dict | |
return nested_set(nested_dict[key], rest) | |
def json_from_arr(arr): | |
nest = lambda: defaultdict(nest) | |
json = nest() | |
for row in arr: | |
nested_set(json, row) | |
return json | |
if __name__ == '__main__': | |
data = [ | |
["BLUE", "XXL", 'H3', 98], | |
["BLUE", "XL", 'H4', 97], | |
["BLUE", "L", 99], | |
["BLUE", "M", 103], | |
["PINK", "XXL", 104], | |
["PINK", "XL", 103], | |
["PINK", "L", 102], | |
["PINK", "M", 100], | |
["RED", "XXL", 99], | |
["RED", "XL", 102], | |
["RED", "L", 109], | |
["RED", "M", 95], | |
] | |
nested_dict = json_from_arr(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment