Split a list of dictionaries into multiple lists of dictionaries in python
本问题已经有最佳答案,请猛点这里访问。
我有一个有16K字典的字典列表。我要将字典列表拆分为多个字典列表。
当前词典列表-
1 2 3 4 5 6 | 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'}] |
期望输出-
1 2 3 4 5 6 7 | 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 2 3 4 5 6 7 8 9 10 11 | 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个子列表的数据。
输出:
1 | [[{'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'}]] |