我有一个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的?
The general idea is
[['server', ''], ['port', '8800'], ['location', '/'], ['location', '/aa'], ['location', 'bb']]
This kind of processing is regarded as a unit (the function is modified from the code you gave), and the recursion is to the extent that it can be processed (because the number of layers may not be 2)Code:
Result:
I think unnecessary code can be removed. Since the problem this time is relatively simple (since it is determined that the bottom layer is a two-element list this time), there is no need to do too much judgment and processing (even this recursive solution can also be used) Change to a simple method).
I'm not sure if there are any other repetitive things in your information besides
location
. I think it's better to process them uniformly, so the values in my dictionary are different from the examples you gave. I use list instead of string. .Break it apart to look better
Others have already taught you how to fish, so your level will not improve if you just ask for fish