11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リストの中にある複数の辞書を集計&ソートする

Last updated at Posted at 2017-10-18

以下のような複数の辞書を持つリストを

base_list = [{'item': 'いちご', 'count': 100},
             {'item': 'りんご', 'count': 30},
             {'item': 'みかん', 'count': 140},
             {'item': 'みかん', 'count': 130},
             {'item': 'りんご', 'count': 10},
             {'item': 'いちご', 'count': 50},
             {'item': 'いちご', 'count': 40}]

以下のようにitemをキーとして集計し、countの値をキーにソートしたい時

result_list = [{'item': 'みかん', 'count': 270},
               {'item': 'いちご', 'count':190},
               {'item': 'りんご', 'count': 40}]

collectionsからdefaultdictとCounterを使って集計、operatorからitemgetterを使ってソートすることによってやれました

from collections import defaultdict, Counter
from operator import itemgetter

base_list = [{'item': 'いちご', 'count': 100},
             {'item': 'りんご', 'count': 30},
             {'item': 'みかん', 'count': 140},
             {'item': 'みかん', 'count': 130},
             {'item': 'りんご', 'count': 10},
             {'item': 'いちご', 'count': 50},
             {'item': 'いちご', 'count': 40}]

count_list = defaultdict(Counter)

for base_dict in base_list:
    counts = Counter({key: value for key, value in base_dict.items() if key not in ('item')})
    count_list[base_dict['item']] += counts

summary_list = [dict(value, item=key) for key, value in count_list.items()]

result_list = sorted(summary_list, key=itemgetter('count'), reverse=True)
11
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?