[英]Convert one level dictionary to structure of nested dictionaries
鑒於這種字典結構:
{
'property1': 'value1',
'property2.property3': 'value2',
'property2.property7': 'value4',
'property4.property5.property6': 'value3',
}
需要轉換為這個樣子:
{
'property1': 'value1',
'property2': {
'property3': 'value2',
'property7': 'value4'
},
'property4': {
'property5': {
'property6': 'value3'
}
}
}
只是簡單的例子。 我想看看最優化和美觀的解決方案。 顯然它應該是將第一個字典作為輸入並輸出第二個字典的函數。
Quick'n'dirty解決方案。 似乎工作,但如果有一個更簡單的方法,我不會感到驚訝。
from collections import defaultdict
def default():
return defaultdict(default)
def convert(src):
dest = default()
for key, val in src.iteritems():
cursor = dest
path = key.split('.')
for path_elem in path[:-1]:
cursor = cursor[path_elem]
cursor[path[-1]] = val
return dest
def to_regular_dict(val):
# optional, if you do not want to carry defaultdicts around
if isinstance(val, defaultdict):
return {key:to_regular_dict(val) for key, val in val.iteritems()}
else:
return val
src = {
'property1': 'value1',
'property2.property3': 'value2',
'property2.property7': 'value4',
'property4.property5.property6': 'value3',
}
print convert(src)
print to_regular_dict(convert(src))
正如我所說,很簡單。
def transform(inp):
destination = {}
for key, value in inp.items():
keys = key.split(".")
d = destination
for key in keys[:-1]:
if key not in d:
d[key] = {}
d = d[key]
d[keys[-1]] = value
return destination
去測試:
inp = {
'property1': 'value1',
'property2.property3': 'value2',
'property2.property7': 'value4',
'property4.property5.property6': 'value3',
}
output = transform(inp)
print output
{'property1': 'value1',
'property2': {
'property3': 'value2',
'property7': 'value4'
}
,'property4': {
'property5': {
'property6': 'value3'
}
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.