owned this note
owned this note
Published
Linked with GitHub
# 辞書(Dictionary)
###### tags: `Python`
辞書(dictionary)型とは、「{}」の中にkeyとvalueの組み合わせが含まれているデータのことです。
:::info
dic = {key1 : value1, key2 : value2, key3 : value3}
:::
のように、辞書型のオブジェクトを構成する要素はkeyとvalueをコロン(:)で区切ったペアになっています。
そして、それぞれのペアはカンマ(,)で区切られています。
**Example:**
| NAME| AGE | EMAIL |
| -------- | -------- | -------- |
| Eric | 21 | 'abc123@gmail.com'|
```python=
dic = {'NAME' : 'Eric', 'AGE' : 21, 'EMAIL' : 'abc123@gmail.com'}
print(dic)
```
**Results:**
```
{'NAME': 'Eric', 'AGE': 21, 'EMAIL': 'abc123@gmail.com'}
```
---
## 空の辞書を作成する
```python=
dict_a = {}
dict_b = dict()
```
* 運用効率については、{}はDict()よりも速くなります。
---
## String型のキーと数値型のキー
### String型のキー
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
```
### 数値型のキー
```python=
dict_key_val = {10: 'グーグル', 100: 'ツイッター', 55: 'アマゾン'}
imas = {765: 'ミリシタ',
346: 'デレステ',
283: 'シャイニーカ'}
```
---
## 要素を取り出す
* ### dict(key)
dict[key]既存の辞書の key に対応するvalueを取り出す。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print(dict['Google'])
```
**Results:**
```
グーグル
```
* ### get(key, default = None)
keyが辞書にあれば key に対する値を、そうでなければ default を返します。default のデフォルトは None です。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print(dict.get('Google', 'xxx'))
print(dict.get('Facebook', 'xxx'))
```
**Results:**
```
グーグル
xxx
```
* ### setdefault(key, default = None)
もし、key が辞書に存在すれば、その値を返します。そうでなければ、値を default として key を挿入し、 default を返します。 default のデフォルトは None です。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
dict.setdefault('Facebook', 'フェースブック')
print(dict)
```
**Results:**
```
{'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン', 'Facebook': 'フェースブック'}
```
* ### keys()
既存の辞書の key のリストを取り出す。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print('keys() = ' , dict.keys())
```
**Results:**
```
keys() = dict_keys(['Google', 'Twitter', 'Amazon'])
```
* ### values()
既存の辞書の value のリストを取り出す。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print('values() = ' , dict.values())
```
**Results:**
```
values() = dict_values(['グーグル', 'ツイッター', 'アマゾン'])
```
* ### items()
items()既存の辞書のオブジェクト(keyとvalue)を返します
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print('items() = ' , dict.items())
```
**Results:**
```
items() = dict_items([('Google', 'グーグル'), ('Twitter', 'ツイッター'), ('Amazon', 'アマゾン')])
```
## 辞書の項目数
### * len()
辞書の項目数を返します
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print('dict n = ', len(dict));
```
**Results:**
```
dict n = 3
```
## 値を追加しますと値を変更します
* ### d(key) = value
d(key) に value を設定します。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
dict['Microsoft'] = 'マイクロソフト' # 追加
dict['Google'] = 'Googol' # 変更
print(dict)
```
**Results:**
```
{'Google': 'Googol', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン', 'Microsoft': 'マイクロソフト'}
```
* ### update({key : value})
辞書の内容をkeyとvalueで変更します。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
dict.update({'Microsoft':'マイクロソフト'}) #追加
dict.update({'Google':'Google'}) #変更
print(dict)
```
**Results:**
```
{'Google': 'Google', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン', 'Microsoft': 'マイクロソフト'}
```
## 辞書のコピー
* ### copy()
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
dict_cp = dict.copy()
print('dict = ' , dict)
print('dict_cp = ' , dict_cp)
```
**Results:**
```
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター'}
dict_cp = {'Google': 'グーグル', 'Twitter': 'ツイッター'}
```
## 要素を削除する
* ### pop()
pop(i) 辞書中の指定された位置(i)にある要素をリストから削除して、その要素を返します。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print('pop() = ', dict.pop('Twitter'))
print(dict)
```
**Results:**
```
pop() = ツイッター
{'Google': 'グーグル', 'Amazon': 'アマゾン'}
```
* ### popitem()
popitem()メソッドは辞書の要素を削除し、そのキーkeyと値valueのタプル(key, value)を返す。どの要素を削除するかは指定できない(random)。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print(dict)
print('pop() = ', dict.popitem())
print(dict)
print('pop() = ', dict.popitem())
print(dict)
print('pop() = ', dict.popitem())
print(dict)
```
**Results:**
```
{'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
pop() = ('Amazon', 'アマゾン')
{'Google': 'グーグル', 'Twitter': 'ツイッター'}
pop() = ('Twitter', 'ツイッター')
{'Google': 'グーグル'}
pop() = ('Google', 'グーグル')
{}
```
要素が空の状態で popitem メソッドを使用すると KeyError エラーが発生します。
```python=
dict = {}
print('pop() = ', dict.popitem())
```
**Results:**
```
KeyError: 'popitem(): dictionary is empty'
```
* ### del d(key)
d から d(key) を削除します。マップに key が存在しなければ、 KeyError を送出します。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
del dict['Amazon']
print('del = ' , dict)
```
**Results:**
```
del = {'Google': 'グーグル', 'Twitter': 'ツイッター'}
```
* ### clear()
辞書の全ての項目を消去します。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
dict.clear()
print('clear = ' , dict)
```
**Results:**
```
clear = {}
```
* ### del d
辞書を削除します。
```python=
del dict
```
## 存在確認
* ### in
in演算子を利用し、辞書に特定のキーを持つペアが存在するか確認できます。
getも出来ます。
```python=
dict = {'Google': 'グーグル', 'Twitter': 'ツイッター', 'Amazon': 'アマゾン'}
print( str('Google' in dict.keys()))
print( str('Google' in dict.values()))
```
**Results:**
```
True
False
```
## ソート
* ### sorted
辞書型には順序がありませんが、ソートで順序を並べることは出来ます。
```python=
dict = {'Google': 100, 'Twitter': 50, 'Amazon': 70}
sortedDict = sorted(dict.values())
print(sortedDict)
dict = {3: 'グーグル', 1: 'ツイッター', 2: 'アマゾン'}
sortedDict = sorted(dict.items())
print(sortedDict)
```
**Results:**
```
[50, 70, 100]
[(1, 'ツイッター'), (2, 'アマゾン'), (3, 'グーグル')]
```
* ### sorted 依照值來排序
```python=
dict = {'Google': 100, 'Twitter': 50, 'Amazon': 70}
sortedDict = sorted(dict.items(), key=lambda item:item[1])
print(sortedDict)
```
**Results:**
```
[('Twitter', 50), ('Amazon', 70), ('Google', 100)]
```
:::warning
## 利用dict()將雙值序列轉成字典
* 內容剛好每一組都是兩項(裡外兩層不管是tuple或list都沒有問題)
```python=
# list(tuple) -> dict
imas_list = [(765, 'ミリシタ'), (346, 'デレステ'), (283, 'シャイニーカ')]
imas_dict = dict(imas_list)
print(imas_dict)
# tuple(list) -> dict
imas_tuple = ([765, 'ミリシタ'], [346, 'デレステ'], [283, 'シャイニーカ'])
imas_dict = dict(imas_list)
print(imas_dict)
```
**Results:**
```
{765: 'ミリシタ', 346: 'デレステ', 283: 'シャイニーカ'}
{765: 'ミリシタ', 346: 'デレステ', 283: 'シャイニーカ'}
```
* 兩個字元的字串會分別被拆開(但超過兩個字元就不支援了)
```python=
str_list = ["ax", "cy", "ez"]
str_dict = dict(str_list)
print(str_dict)
```
**Results:**
```
{'a': 'x', 'c': 'y', 'e': 'z'}
```
## 利用zip()建立字典
```python=
asciidict = dict(zip(range(97, 101), "abcd"))
print(asciidict)
id_list = [765, 346 ,283 ]
name_list = ['ミリシタ', 'デレステ', 'シャイニーカ']
imas_dict = dict(zip(id_list, name_list))
print(imas_dict)
```
**Results:**
```
{97: 'a', 98: 'b', 99: 'c', 100: 'd'}
{765: 'ミリシタ', 346: 'デレステ', 283: 'シャイニーカ'}
```
:::