2

I have a requirement where I have keys in string format combined by dot (.) and the value associated with that string of key and I want to create a dictionary.

key1 = "A.B.C.D"
text_to_be_inserted1_for_key1 = "Test1"
key2 = "A.B.C.E"
text_to_be_inserted_for_key2 = "Test2"

Expected result

dict = {
    "A": {
        "B" : {
            "C" : {
                "D" : text_to_be_inserted1_for_key1,
                "E" : text_to_be_inserted_for_key2 
            }
        }
    }
}
1

3 Answers 3

6
from collections import defaultdict

def deep_dict():
    return defaultdict(deep_dict)

result = deep_dict()

def deep_insert(key, value):
    d = result
    keys = key.split(".")
    for subkey in keys[:-1]:
        d = d[subkey]
    d[keys[-1]] = value

deep_insert("A.B.C.D", "Test1")
deep_insert("A.B.C.E", "Test2")

import json
print(json.dumps(result, indent=4))
Sign up to request clarification or add additional context in comments.

1 Comment

Im a big fan of avoiding the duplicate -1 indexing if possible, so I believe you could do the same thing more elegantly via by using the splat unpacking feature. *keys, final = key.split(".") for subkey in keys: d = d[subkey] d[final] = value
2

You may

  • for each letter except the last one, create a mapping with the key and a dict
  • for the last letter create the mapping with the value
def insert(keys, values):
    res = {}
    for k, v in zip(keys, values):
        res_tmp = res
        levels = k.split(".")
        for level in levels[:-1]:
            res_tmp = res_tmp.setdefault(level, {})
        res_tmp[levels[-1]] = v
    return res

Use

key1 = "A.B.C.D"
value_key1 = "Test1"
key2 = "A.B.C.E"
value_key2 = "Test2"

result = insert([key1, key2], [value_key1, value_key2])

print(result) # {'A': {'B': {'C': {'D': 'Test1', 'E': 'Test2'}}}}

Comments

-1

You can solve for each case and then merge

from copy import deepcopy

def dict_of_dicts_merge(x, y):
    z = {}
    overlapping_keys = x.keys() & y.keys()
    for key in overlapping_keys:
        z[key] = dict_of_dicts_merge(x[key], y[key])
    for key in x.keys() - overlapping_keys:
        z[key] = deepcopy(x[key])
    for key in y.keys() - overlapping_keys:
        z[key] = deepcopy(y[key])
    return z

key1 = "A.B.C.D"
text_to_be_inserted_for_key1 = "Test1"
key2 = "A.B.C.E"
text_to_be_inserted_for_key2 = "Test2"

dict1 = {}
newdict = {}
olddict = {}
keys_for_1 = key1.split(".")
keys_for_1.reverse()


olddict[keys_for_1[0]] = text_to_be_inserted_for_key1

for i in range (1,len(keys_for_1)):
    newdict = {}
    newdict[keys_for_1[i]] = olddict
    olddict = newdict

save1 = newdict 

newdict = {}
olddict = {}
keys_for_2 = key2.split(".")
keys_for_2.reverse()
olddict[keys_for_2[0]] = text_to_be_inserted_for_key2

for i in range (1,len(keys_for_2)):
    newdict = {}
    newdict[keys_for_2[i]] = olddict
    olddict = newdict 

save2 = newdict

dict1 = dict_of_dicts_merge(save1,save2)
print (dict1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.