Python Collections Counter for a List of Dictionaries

前端 未结 2 1144
时光取名叫无心
时光取名叫无心 2021-01-18 16:59

I have a dynamically growing list of arrays that I would like to add like values together. Here\'s an example:

{\"something\" : [{\"one\":\"200\"}, {\"three\         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 17:29

    One way would be do as follows:

    from collections import defaultdict
    
    d = {"something" :
         [{"one":"200"}, {"three":"400"}, {"one":"100"}, {"two":"800"}]}
    
    dd = defaultdict(list)
    
    # first get and group values from the original data structure
    # and change strings to ints
    for inner_dict in d['something']:
        for k,v in inner_dict.items():
            dd[k].append(int(v))
    
    
    # second. create output dictionary by summing grouped elemetns
    # from the first step.
    out_dict =  {k:sum(v) for k,v in dd.items()}
    
    print(out_dict)
    # {'two': 800, 'one': 300, 'three': 400}
    

    In here I don't use counter, but defaultdict. Its a two step approach.

提交回复
热议问题