简体   繁体   English

将嵌套列表转换为字典,其中列表的第一个元素是字典的键

[英]Convert nested list to dict where first element of list is key for dict

I have list , 我有清单,

[['1', '4.00', 'A'],
['1', '5.00', 'B'],
['2', '4.00', 'V'],
['1', '12.00', 'C'],
['3', '4.00', 'R']]

How can I convert this list to, 我如何将该列表转换为

{'1': [{'total': 21}, {'data': [['A'], ['B'], ['C']]}]}
{'2': [{'total': 4}, {'data': ['C']}]}
{'3':....}

First of all we sort the data which would sort the nested lists based upon the initial elements and hence we get nested list with the elements sorted on the first index of list inside the nested list, then we simply groupby() them on the first element. 首先,我们对数据进行排序,该数据将根据初始元素对嵌套列表进行排序,因此我们得到嵌套列表,其中的元素在嵌套列表内的列表的第一个索引上排序,然后我们在第一个元素上进行groupby()

import itertools

a= [['1', '4.00', 'A'],
   ['1', '5.00', 'B'],
   ['2', '4.00', 'V'],
   ['1', '12.00', 'C'],
   ['3', '4.00', 'R'],
]

a.sort()

dictionary = {}
group = itertools.groupby(a, key = lambda x:x[0])
for k,g in group:
   ans = 0
   alphabets = []
   for i in g:
      ans+=(float(i[1]))
      alphabets.append([i[2]])
   dictionary[k] = [{'total':ans}, {'date':alphabets}]

print dictionary

>>> {'1': [{'total': 21.0}, {'date': [['C'], ['A'], ['B']]}], '3': [{'total': 4.0}, {'date': [['R']]}], '2': [{'total': 4.0}, {'date': [['V']]}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM