I need to create a json file , given a dictionary of paths and their values. I written some code for adding an entry, that looks like it functions and result is correct, but as somebody who new in python, I wonder how can this be improved, and if there is a function that does the same, already exist in modules included with python 2.7?
def path_to_list(path):
if isinstance(path, (str,)):
map_list = path.split("/")
for i, key in enumerate(map_list):
if key.isdigit():
map_list[i] = int(key)
else:
map_list = path
return map_list
def add_to_dictionary(dic, keys, value):
for i, key in enumerate(keys[:-1]):
if i < len(keys)-1 and isinstance(keys[i+1], int):
# Case where current key should be a list, since next key is
# is list position
if key not in dic.keys():
# Case list not yet exist
dic[keys[i]] = []
dic[keys[i]].append({})
dic = dic.setdefault(key, {})
elif not isinstance(dic[key], list):
# Case key exist , but not a list
# TO DO : check how to handle
print "Failed to insert " + str(keys) + ", trying to insert multiple to not multiple "
break
else:
# Case where the list exist
dic = dic.setdefault(key, {})
elif i < len(keys)-1 and isinstance(key, int):
# Case where current key is instance number in a list
try:
# If this succeeds instance already exist
dic = dic[key]
except (IndexError,KeyError):
# Case where list exist , but need to add new instances ,
# as key instance not exist
while len(dic)-1 < key:
dic.append({})
dic = dic[key]
else:
# Case where key is not list or instance of list
dic = dic.setdefault(key, {})
# Update value
dic[keys[-1]] = value
my_dict1 ={}
add_to_dictionary(my_dict1, path_to_list("a/0/b/c"), 1)
print my_dict1
{'a': [{'b': {'c': 1}}]}
add_to_dictionary(my_dict1, path_to_list("a/2/b/c"), "string")
print my_dict1
{'a': [{'b': {'c': 1}}, {}, {'b': {'c': 'string'}}]}
add_to_dictionary(my_dict1, path_to_list("a/2/b/c"), "new string")
print my_dict1
{'a': [{'b': {'c': 1}}, {}, {'b': {'c': 'new string'}}]}
Some keys may already exist, then I update just the value.
Numeric keys indicate that key before it can have multiple values, and I'm adding/updating value in this place in array