我需要创建一个 json 文件,给出路径及其值的字典。我编写了一些用于添加条目的代码,看起来它的功能和结果是正确的,但是作为 Python 新手,我想知道如何改进这一点,如果有一个功能相同的功能,模块中已经存在包含在 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
一些键可能已经存在,然后我只更新值。
数字键在它可以有多个值之前表示该键,我正在数组中的这个地方添加/更新值
慕尼黑的夜晚无繁华
相关分类