最近面试做了这样一个题:'''Given a “flatten” dictionary object, whose keys are dot-separated. For example, { ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}. Implement a function in any language to transform it to a “nested” dictionary object. In the above case, the nested version is like:
{
‘A’: 1,
‘B’: {
‘A’: 2,
‘B’: 3,
},
‘CC’: {
‘D’: {
‘E’: 4,
‘F’: 5,
}
}
}
It’s guaranteed that no keys in dictionary are prefixes of other keys.'''
答案(python做的):
d = {'A': 1, 'B.A': 2, 'B.B': 3, 'CC.D.E': 4, 'CC.D.F': 5}
new_d = {}
for key in d:
if "." not in key:
new_d[key] = d[key]
else:
lst = key.split(".")
l = len(lst)
now_d = new_d
for i in range(l - 1):
try:
now_d[lst[i]]
except:
now_d[lst[i]] = {}
now_d = now_d[lst[i]]
now_d[lst[-1]] = d[key]
print(new_d)
{'B': {'B': 3, 'A': 2}, 'CC': {'D': {'E': 4, 'F': 5}}, 'A': 1}