在python中将字典列表拆分为多个字典列表

时间:2017-07-18 00:50:03

标签: python list dictionary

我有一个包含16k字典的词典列表。我想将字典列表拆分成多个字典列表。

当前词典列表 -

list = [{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'},
        {'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'},
        {'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'}, 
        {'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'}, 
        {'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'}, 
        {'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]

期望的输出 -

list1 = [{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'},
         {'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'},
         {'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'}]

list2 = [{'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'}, 
         {'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'}, 
         {'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

l = [{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'},
    {'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'},
    {'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'}, 
    {'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'}, 
    {'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'}, 
    {'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]

n = 3
n1 = len(l)//n
new = [l[i:i+n1] for i in range(0, len(l), n1)]
print new

此代码现在创建一个列表,其中包含分为n个子列表的数据。

输出:

[[{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'}, {'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'}], [{'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'}, {'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'}], [{'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'}, {'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]]