问 题
我有一个list如下
[[['server', ''],['port','8800'],['location','/'],['location','/aa'],['location','bb']],[['server', ''],['port','80'],['location','/'],['location','/aa'],['location','bb']]]
想要得到如下的dict
[{'server': '','port': '8800','location': '/,/aa,/bb'},{'server': '','port': '80','location': '/,/aa,/bb'}]
或者
[{'server': '','port': '8800','location': '/'},{'server': '','port': '8800','location': '/aa'},{'server': '','port': '8800','location': '/bb'},{'server': '','port': '80','location': '/'},{'server': '','port': '80','location': '/aa'},{'server': '','port': '80','location': '/bb'}]
求解
之前有sf上的同学给出了一个例子
def turn2dic(lst):
global key, value
dic = {}
if all([not isinstance(item, list) for item in lst]):
if len(lst) == 2:
key, value = lst
elif len(lst) == 1:
key=lst[0]
value=''
elif len(lst) == 3:
key=lst[0]
value=lst[1]
dic[key] = value
else:
for item in lst:
subdic = turn2dic(item)
print subdic
dic.update(subdic)
print dic
return dic
但是这个上面代码里,location是覆盖的,因为dic.update(subdic),有什么办法是append的?
解决方案
def single_turn2dic(lst):
global key, value
dic = {}
if all([not isinstance(item, list) for item in lst]):
if len(lst) == 2:
key, value = lst
elif len(lst) == 1:
key = lst[0]
value = ''
elif len(lst) == 3:
key = lst[0]
value = lst[1]
# dic[key] = value
if value and dic.get(key, ''):
dic[key] += ',' + value
else:
dic[key] = value
else:
for item in lst:
subdic = single_turn2dic(item)
# print subdic
# dic.update(subdic)
for name, name_value in subdic.iteritems():
if name_value and dic.get(name, ''):
dic[name] += ',' + name_value
else:
dic[name] = name_value
# print dic
return dic
servers = [[['server', ''], ['port', '8800'], ['location', '/'], ['location', '/aa'], ['location', 'bb']],
[['server', ''], ['port', '80'], ['location', '/'], ['location', '/aa'], ['location', 'bb']]]
def beautify(servers):
# lst = []
if not isinstance(servers[0][0], list):
return single_turn2dic(servers)
else:
return [beautify(server) for server in servers]
print beautify(servers)
大致思路就是 [['server', ''], ['port', '8800'], ['location', '/'], ['location', '/aa'], ['location', 'bb']] 这种的视为一个单元处理(函数修改自你给的代码),递归到可以处理程度(因为层数可能不为2)
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起