質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

2回答

733閲覧

dict型からの変換

1mzmk

総合スコア42

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2021/09/14 12:00

python

1dict = [ 2 { 3 'search_id': 3, 4 'trend': 'word' 5 }, 6 { 7 'search_id': 3, 8 'trend': 'wordA' 9 }, 10 { 11 'search_id': 2, 12 'trend': 'word' 13 } 14]

上のdictのtrendキーのsorezoreno
出現した固有のvalueの回数を求めて、下のような出力を出したいと考えています。

python

1[ 2 { 3 'trend': 'word', 4 'volume': 2 5 }, 6 { 7 'trend': 'wordA', 8 'volume': 1 9 } 10]

しかし、どのようにすれば実現できるかわかりません。
下のようなコードを書いて実行したのですが、キーのみの出力で上のような出力したい出力になりません。

python

1import collections 2a = [i["trend"]for i in dict] 3counts = collections.Counter(a) 4for count in counts: 5 res = ({count: counts[count]}) 6 res = {'topic': count, 'volume': counts[count]} 7 print([x for x in res]) 8 9#出力 10['topic', 'volume'] 11['topic', 'volume']

どのように書けば実現できますでしょうか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

python

1import collections 2mydict = [ 3 { 4 'search_id': 3, 5 'trend': 'word' 6 }, 7 { 8 'search_id': 3, 9 'trend': 'wordA' 10 }, 11 { 12 'search_id': 2, 13 'trend': 'word' 14 } 15] 16a = [i["trend"] for i in mydict] 17counts = collections.Counter(a) 18ans = [] 19for count in counts: 20 dict_temp = {'trend': count, 'volume': counts[count]} 21 ans.append(dict_temp) 22print(ans) 23# [{'trend': 'word', 'volume': 2}, {'trend': 'wordA', 'volume': 1}]

投稿2021/09/14 12:23

ikapy

総合スコア1167

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

dict を変数名に使うと、組み込みのdictと被るんで、避けた方がええでー

python3

1from collections import Counter 2 3data = [ 4 { 5 'search_id': 3, 6 'trend': 'word' 7 }, 8 { 9 'search_id': 3, 10 'trend': 'wordA' 11 }, 12 { 13 'search_id': 2, 14 'trend': 'word' 15 } 16] 17 18cnt = Counter(map(lambda e: e['trend'], data)) 19 20result = [{'trend': t, 'volume': v} for t, v in cnt.items()] 21 22print(result) 23

[{'trend': 'word', 'volume': 2}, {'trend': 'wordA', 'volume': 1}]

投稿2021/09/14 12:23

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問