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?

More than 1 year has passed since last update.

【python】勉強メモ-その6 辞書について

Last updated at Posted at 2022-12-18

1.はじめに

今回は、完全に自分用のメモとなります。

value(値)の取得方法
sample_01.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

ans = favorite_languages["Jane"]
print(ans)

result.txt
python
.get() 存在しないキーにアクセスした場合のエラーハンドリング

dict.get("key", "返すメッセージ")
第二引数を省略した場合は、Noneが返される。

sample_02.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

ans = favorite_languages.get("Taro", "そのキーは存在しません")
print(ans)

result.txt
そのキーは存在しません

.items() キーと値のループ取得

sample_03.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

for key, value in favorite_languages.items():
    print(f"\nキー: {key}")
    print(f"値: {value}")
result.txt
キー: Jane
値: python

キー: Sarah
値: c

キー: Ed
値: ruby

キー: Philip
値: python

.keys() キーを取得

sample_04.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

for key in favorite_languages.keys():
    print(key)
result.txt
Jane
Sarah
Ed
Philip

なお、キーの取得は、ループを使わなくても可能

sample_05.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

print(favorite_languages.keys())

result.txt
dict_keys(['Jane', 'Sarah', 'Ed', 'Philip'])

.values() 値の取得

sample_06.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

for value in favorite_languages.values():
    print(value)
result.txt
python
c
ruby
python

なお、値の取得は、キーと同様に、ループを使わなくても可能。

sample_07.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

print(favorite_languages.values())

result.txt
dict_values(['python', 'c', 'ruby', 'python'])

set() 辞書の値重複排除について

辞書の値を取得する時、重複した値があることがあります。重複した値の排除については、
set()を利用します。sample_06.pysample_08.pyを比較してみてください。

for value in set(favarit_langes.values()):

sample_08.py
favorite_languages = {
    "Jane": "python",
    "Sarah": "c",
    "Ed": "ruby",
    "Philip": "python",
}

for value in set(favorite_languages.values()):
    print(value)
result.txt
python
c
ruby
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?