Last active
August 8, 2018 11:44
-
-
Save blanklin030/c294faef13767c63a4f8c5a57e4b44e8 to your computer and use it in GitHub Desktop.
python递归调用,多维度变化为一个维度,一个维度变化为多个维度
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
# 多维度切为单维度 | |
def go(params): | |
ret = {} | |
for(key,value) in params.items(): | |
if type(value) == str: | |
ret[key] = value | |
elif type(value) == dict: | |
for (k1,v1) in value.items(): | |
new_key = key + "." + k1 | |
new_dict = {new_key: v1} | |
ret.update(go(new_dict)) | |
return ret | |
# 单维度切回多维度 | |
def back(params): | |
ret = {} | |
for(key, value) in params.items(): | |
is_find = key.find(".") | |
if is_find <= 0: | |
ret[key] = value | |
continue | |
new_parent_key = key.split(".")[0] | |
new_key = key.replace(new_parent_key+".", "") | |
is_find = new_key.find(".") | |
if is_find <= 0: | |
ret[new_parent_key] = {new_key: value} | |
continue | |
new_params = {new_key: value} | |
ret[new_parent_key].update(back(new_params)) | |
return ret | |
params = { | |
"a": "a", | |
"b": { | |
"c": "c", | |
"d": { | |
"d": "d" | |
}, | |
} | |
} | |
print(params) | |
params = go(params) | |
print(params) | |
params = back(params) | |
print(params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment