5.1 辞書データの種類
辞書インデックスだけではなく、整数、データの多くの異なる種類を使用することができます。インデックス辞書はキー、「キー」と呼ばれ、その値は「キー - 値」と呼ばれるコードに対場合、中括弧付き入力辞書{}。
辞書はスライス画像として表示されませんので、辞書のエントリは、順序付けされていません。
5.1.1 キー()、値()とアイテム()メソッド
キー()、値()とアイテム()メソッドは、キー、およびキー値を辞書に対応し、それぞれ、同様の値のリストを返す - 値のペア。真の価値は、彼らは、何のAPPEND()メソッドを変更することはできません、これらのメソッドによって返されたリストではありません。しかし、これらのデータ型は、ループのために使用することができます。
>>> spam = {'color':'red','age':42}
>>> for i in spam.values():
print (i)
red
42
()メソッドは、リストとしてリストを辞書に変換することができます
>>> list(spam.keys())
['color', 'age']
>>> list(spam.values())
['red', 42]
>>> spam
{'color': 'red', 'age': 42}
5.1.2 GET()メソッドは、SetDefault()メソッド
キーの値を取得するには、キーが存在しない場合、代替リターン値:get()メソッドは、2つのパラメータをとり
SetDefault()メソッドは、メソッドの最初のパラメータを渡す方法を提供するキーをチェックすることで、2番目のパラメータは、キーが存在しない場合に設定される値です。キーは、リターンキーに存在する場合。
プログラムはPPRINT()モジュールを導入する場合は、PPRINT()とpformat()印刷の辞書を使用することができます。
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(pprint.pformat(count))
#pprint.pprint(count) print(pprint.pformat(count))这两种表达式等价
結果:
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
5.2 練習プログラム
- アイテムのリストの楽しいゲーム
あなたは楽しいビデオゲームを作成します。選手リスト項目のデータ構造モデリングのための辞書です。キーは、項目のリストを記述した文字列が、ある場合には、値が整数値は、記事どのように多くの選手を示し、です。例えば、辞書値{ 'ロープ':1、 'トーチ':6 '金貨':42 '短剣':1、 '矢印':12}プレイヤーがロープを有することを意味し、6つのトーチ、42金のように。可能な項目の任意のリストを受け取り、以下の通りですdisplayInventory()という名前の関数を、書きます:
Inventory:
1 rop
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items : 62
コードは以下の通りであります:
def displayInventory(dic):
print('Inventory:')
count = 0
for k, v in dic.items():
print(str(v) + ' ' + k)
count = v+count
print('Total number of items : ', count)
dicValue = {'rop': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
displayInventory(dicValue)
- このトロフィーは、文字列のリストとして表現されると仮定し、ワンストップの征服。
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby']
在庫は、addedItems引数はちょうどdragonLootのように、リスト項目のプレイヤーのリストを表す辞書(前の項目と同じ)であるされた機能addToInventory(在庫、addedItems)の名前を、書きます。addToInventory()関数は、アイテムの更新リストを表す辞書を返す必要があります。
def displayInventory(dic):
print('Inventory:')
count = 0
for k, v in dic.items():
print(str(v) + ' ' + k)
count = v+count
print('Total number of items : ', count)
def addToInventory(inventory, addeditems):
for i in addeditems:
if i in inventory.keys():
inventory[i] += 1
else:
inventory.setdefault(i, 1)
return inventory
inv = {'gold coin':42, 'rope':1}
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)
前のプログラム(プラス以前のプロジェクトのdisplayInventory()関数)次の出力:
Inventory:
45 gold coin
1 rope
1 digger
1 ruby
Total number of items : 48