LoginSignup
3
0

辞書型のリストの取り出し

Pythonの辞書型リストの扱いについて説明するよ。
以下のようなリストから値を取り出す操作を書くよ。

dict_list = [{"name": "apple", "price": 150, "country": "Japan"},{"name": "orange", "price": 200, "country": "America"}, {"name": "pineapple ", "price": 200, "country": "Philippines"}]

リストから辞書型を取り出す

1. リストから辞書型を1つずつ取り出す

for文を使って、1つずつ取り出すよ。

for item in dict_list:
    print(item)

# 出力結果
> {'name': 'apple', 'price': 150, 'country': 'Japan'}
> {'name': 'orange', 'price': 200, 'country': 'America'}
> {'name': 'pineapple ', 'price': 200, 'country': 'Philippines'}

2.リストから、2番目の要素のみを取り出す

listの要素番号を指定して取り出すよ。リスト名に[要素番号]をつければいいけど、要素番号は0から始まるのが注意だよ。

dict_orange = dict_list[1]
print(dict_orange)

# 出力結果
> {'name': 'orange', 'price': 200, 'country': 'America'}

3.リストから、全ての辞書型のnameの値を取り出す

辞書型のリストから、nameの値のみを取り出すよ。
リスト内法表記を利用するよ。

name_list = [item['name'] for item in dict_list]
print(name_list)

# 出力結果
> ['apple', 'orange', 'pineapple ']

4.全ての辞書型のキーを減らす

辞書型のkey'country'を減らし、リスト化するよ。

delete_country = list()
for item in dict_list:
    del item['country']
    delete_country.append(item)
print(delete_country)

# 出力結果
>  [{'name': 'apple', 'price': 150}, {'name': 'orange', 'price': 200}, {'name': 'pineapple ', 'price': 200}]

5.特定の値を取り出して、辞書型のリストを作る

dict_listから、namepriceを抽出するよ。
リスト内法表記で辞書型を作っていくよ。

pic_up_name_price = [{'name': item['name'], 'price': item['price']} for item in dict_list]
print(pic_up_name_price)

# 出力結果
> [{'name': 'apple', 'price': 150}, {'name': 'orange', 'price': 200}, {'name': 'pineapple ', 'price': 200}]

まとめ

辞書型の扱いにもまだまだたくさんあるけれど、使いそうなものをまとめたよ。
慣れると辞書型って便利そう。。。

3
0
1

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
3
0