python 多层list 转dict问题
大家讲道理
大家讲道理 2017-04-17 17:54:24
0
4
449

我有一个list如下

list=[[['upstream', 'aa'], [['server', '172.16.1.6']]], [['upstream', 'bb'], [['server', '172.16.1.6:8080']]], [['server'], [['listen', '80'], ['server_name', 'aaa.test.com']]]]

类似上面的,可能还有更多层嵌套

请问这样的list,我怎么转换成dict

最好是类似

{'upstream:aa','server:172.16.1.6'}

这种

请注意,list里[]是分块的,这个分块对解析有意义,所以不能完全使用flatten()之类的压平。否则解析的时候就乱了。

目前 松林给出的代码,运算出来的答案是我想要的,不过实际上我的列表嵌套层数还更多一些。

不知道怎么解决。。

============================

更新问题

首先感谢各位的答案

其次,楼下第一的答案
如果这个list里有key是一样的,但是value可能有两个以上,比如

[[['location', '/']
.........
[['location', '~', '.*\.(ico|gif|jpg|jpeg|png|bmp|swf)$']]]]

在一个大的[]里,出现两次location,并且第二次的location有2个以上的value

[['location', '/']被后面的覆盖,而后面的因为有2个value,导致不满足key, value = lst if len(lst)==2 else (lst[0], ''),于是匹配不到[['location', '/']

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
洪涛

I wrote one, just to test the example you gave me, and see if it’s what you want:

lst=[
        [
            ['upstream', 'aa'], 
            [
                ['server', '172.16.1.6']
            ]
        ],
        [
            ['upstream', 'bb'],
            [
                ['server', '172.16.1.6:8080']
            ]
        ],
        [
            ['server'], 
            [
                ['listen', '80'],
                ['server_name', 'aaa.test.com']
            ]
        ]
    ]
def turn2dic(lst):
    dic = {}
    if all([not isinstance(item, list) for item in lst]):
        key, value = lst if len(lst)==2 else (lst[0], '')
        dic[key] = value
    else:
        for item in lst:
            subdic = turn2dic(item)
            dic.update(subdic)
    return dic

results = []

for item in lst:
    results.append(turn2dic(item))

print results
阿神

You can do this

ret = []
for i in lst:
    d = {}
    d[i[0][0]] = i[0][1] if len(i[0])>1 else ''
    d.update({k:v for k, v in i[1]})
    ret.append(d)
print ret

Results

[{'server': '172.16.1.6', 'upstream': 'aa'},
 {'server': '172.16.1.6:8080', 'upstream': 'bb'},
 {'listen': '80', 'server': '', 'server_name': 'aaa.test.com'}]
小葫芦

Under what circumstances would such an inhumane list be designed?

左手右手慢动作

Is there an idea like this? First convert the list into a string
Then run a while loop and use the replace function to replace the square brackets
For example, '[[[' is replaced with '3', ']]' is replaced with ' -2'
Then cumsum the replaced number
Once you get 1, cut it and you can get the result
Try it, if it doesn't work, come up with the code

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template