首页 > 解决方案 > 从列表创建字典

问题描述

我有一个"testlist"包含 4x 子列表的列表

[
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]

我想从“testlist”中获取以下字典

{group1:[name1,name2], group2:[name3,name4]}

我在这里有一小段代码,它从每个子列表中获取“组”元素,然后使用获取的元素作为键更新字典。我坚持的是如何填充这些键的值?

def test():
dic={}
testlist = [
            [name1,ip1,mask1,group1],
            [name2,ip2,mask2,group1], 
            [name3,ip3,mask3,group2],
            [name4,ip4,mask4,group2]
           ]
for each in testlist:
    dic.update{each[3]:[]}

标签: python

解决方案


在列表上使用“传统”循环(假设 name1、ip1 等在某处定义):

def test():
    dic = {}
    testlist = [
        [name1, ip1, mask1, group1],
        [name2, ip2, mask2, group1],
        [name3, ip3, mask3, group2],
        [name4, ip4, mask4, group2]
    ]
    for each in testlist:
        if each[3] not in dic:
            dic[each[3]] = []

        dic[each[3]].append(each[0])

    return dic

推荐阅读