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?

python 辞書

Last updated at Posted at 2024-04-29
はじめに

辞書は、キー(key):値(value)のペアの集合体で、キーは、一意でなければならない。波括弧{}で辞書を生成する。

hyoko = {'fuji':3777,'hodaka':3190,'tsurugi':2777}

#要素の追加
hyoko['hakuba']=2932
print(hyoko)#{'fuji': 3777, 'hodaka': 3190, 'tsurugi': 2777, 'hakuba': 2932}
#要素の削除
del hyoko['hodaka']
print(hyoko)#{'fuji': 3777, 'tsurugi': 2777, 'hakuba': 2932}

辞書のitems()メソッドを使うと、ループでキーと値を同時に取り出せる。forの後にループ用変数を2つ記載する。1つ目の変数が辞書のキー、2つ目の変数が辞書の値となる。

hyoko = {'fuji':3777,'hodaka':3190,'tsurugi':2777}
for mtname,height in hyoko.items():
    print(mtname,height)
reference Excel VBA の辞書
'宣言
Dim hyoko As Object
Set hyoko = CreateObject("Scripting.Dictionary")
'要素の追加
hyoko.Add "fuji", 3777
hyoko.Add "hodaka", 3190
hyoko.Add "tsurugi", 2777
'ループ
''インデックスでループ
Dim i As Long
Dim keys_ As Variant
keys_ = hyoko.keys
For i = 0 To hyoko.Count - 1
    Debug.Print keys_(i)
    Debug.Print hyoko.Item(keys_(i))
Next i
''キーでループ
Dim key As Variant
For Each key In hyoko
   Debug.Print key
   Debug.Print hyoko.Item(key)
Next key
''値でループ
Dim itm As Variant
For Each itm In hyoko.items()
    Debug.Print itm
Next itm

参考:Guido van Rossum.Python チュートリアル.O'REILLY,第5章

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?