python 遍历 list中 dict_python - 遍历list,转换成dict

问 题

我有一个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屋 ” ,选择关注与百万开发者在一起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值