0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

辞書内包表記(dict comprehension)は、既存の辞書やイテラブルオブジェクトから新しい辞書を作成する際に便利な記法です。リスト内包表記に似ていますが、辞書の場合はキーと値のペアを指定する必要があります。

基本的な構文

new_dict = {key_expr: value_expr for var in iterable}
  • key_expr: 新しい辞書のキーを生成する式
  • value_expr: 新しい辞書の値を生成する式
  • var: イテラブルオブジェクトからキーと値を生成するための変数
  • iterable: キーと値の元となるイテラブルオブジェクト(リスト、タプル、range()など)

シンプルな例

squares = {x: x**2 for x in range(1, 6)}
print(squares) # 出力: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

上記の例では、1から5までの整数をキーとし、そのキーの2乗の値が辞書のValueとして設定されています。

条件付きの辞書内包表記

even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # 出力: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

ifを使うことで、辞書に含める要素を条件付きで指定できます。

2つのイテラブルから辞書を作成

names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 92]

# zip()関数を使って2つのイテラブルから辞書を作成
records = {name: score for name, score in zip(names, scores)}
print(records) # 出力: {'Alice': 90, 'Bob': 85, 'Charlie': 92}

zip()関数を使えば、2つのイテラブルから辞書を簡単に作成できます。
辞書内包表記を活用することで、コードをコンパクトに記述でき、可読性も向上します。ただし、複雑な式になると可読性が低下する可能性があるので、適切に利用する必要があります。

参考) 東京工業大学情報理工学院 Python早見表

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?