Python Functions, Files, and Dictionaries2: Dictionary

Dictionary

複数のペアが同じ最初のデータ要素を共有しているデータペアのコレクションがある場合、辞書を使用することはできません。

リストと辞書の使い分けを経験した今、それぞれの状況に応じてどちらを使うのがベストかを判断する必要があります。以下のガイドラインは、ディクショナリが有益である場合を認識するのに役立ちます。

1つのデータが1つの項目のプロパティのセットで構成されている場合、多くの場合、辞書の方が優れています。郵便番号のプロパティがリストのインデックス 2 にあることを精神的に追跡しようとすることもできますが、mylst[2] を調べるよりも mydiction[‘zipcode’] を調べる方がコードは読みやすく、ミスも少なくなるでしょう。

データペアのコレクションがあり、その最初の値に基づいてペアの1つを調べる必要がある場合は、(キー、値)タプルのリストよりも辞書を使用する方がよいでしょう。辞書を使用すると、キーを調べることによって、任意の(キー、値)タプルの値を見つけることができます。タプルのリストでは、リストを繰り返し、各ペアが目的のキーを持っているかどうかを調べる必要があります。

  • To introduce the idea of Key, Value pairs
  • To introduce the idea of an unordered sequence
  • To understand the use of parallel construction in lists
  • To understand the performance benefit and simplicity of a dictionary over parallel lists
  • To understand that dictionary iteration iterates over keys

dictionaryといえば.item()でtuple取得。

Dictionary は Keyとそれに対応するvalueを持つ。

curly braces {}を使って辞書を生成

medals = {"gold":33, "silver":17,"bronze":12}
print(medals)
print("insertも可能")
medals2 = {}
medals2["gold"] = 12
medals2["silver"] = 4
medals2["bronze"] = 5
print(medals2)
print("keyを指定してvalueを取得")
print(medals2["silver"])
#print(medals2[4]) #error

辞書にkey-value pairを足す方法、valueを変更する、key-value pairを消す。

Dictionaryは中身を変えてもid変化しない。

.keys()メソッドはkey-value pairの順番を再現しないことに注意。

value is associated with key

dictonaryの中身を取得する(探し物する)メソッドは、lilst()にしないと使えない。

.keys()メソッド,.valuesメソッドはlistをreturnしないから

list()でlistにしてあげなきゃね

inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}

print(list(inventory.keys()))
print(inventory.keys())
print(type(inventory.keys()))
for k in inventory:
print(k)
print(list(inventory.values()))
for v in inventory.values():
print(v)
print(list(inventory.items()))
for k, v in inventory.items():
print(k, v)

travel = {“North America”: 2, “Europe”: 8, “South America”: 3, “Asia”: 4, “Africa”:1, “Antarctica”: 0, “Australia”: 1}

print(list(travel.values()))
total = 0
for v in list(travel.values()):
if v != 0:
total = total + v

dictionaryの中に探しているkeyがないとerrorを起こすので、あるかないかを調べるといい。

inventory = {‘apples’: 430, ‘bananas’: 312, ‘oranges’: 525, ‘pears’: 217}
print(‘apples’ in inventory)
print(430 in inventory) #valueからは探せない?

if ‘bananas’ in inventory:
print(inventory[‘bananas’])
else:
print(“We have no bananas”)

keyがないとエラーが出るので.get(key)でvalueをgetする (.get()メソッドの使い方その2)

if cherries is in our dictionary as a key then get the value associated with it. If cherries is not a key in our dictionary, then just use this as the value. This isn’t going to add a key value pair with cherries, it’s instead just going to say the value of this overall expression should be zero. もしcherriesがキーとして辞書にあれば、それに関連する値を取得します。cherriesが辞書のキーでない場合は、これを値として使用します。これは、cherriesのキーと値のペアを追加するのではなく、この式全体の値をゼロにすることを意味します。

inventory = {‘apples’: 430, ‘bananas’: 312, ‘oranges’: 525, ‘pears’: 217}

print(inventory.get(“apples”))
print(inventory[“apples”])
print(inventory.get(“cherries”))
#print(inventory[“cherries”]) これを入れるとerrorが出る。

print(inventory.get(“cherries”,0))
print(inventory.get(“apples”,0))

dictionary はaliasを作れる。mutable.

探し物がいくつあるか調べたい時

accum = 0

for i in 探物をするsequence

if i = 探物:

accum += 1

elementを片っ端から数え上げるコード!!!!dictionaryの力!!!すごい!!!!!

cs = {}

forin sequence:
   cs = cs.get(c, 0) + 1

より一般化したもの

5155回出てきているのはスペースではなく\n”

完全無欠版

stri = “what can I do”

char_d = {}
for c in stri:
if c not in char_d:
char_d = 0
char_d = char_d + 1

char_d = {}
for c in stri:
char_d = char_d.get(c, 0) + 1

print(char_d)

text内の行の数を特定する

file.readlines()はtext fileの各行をitemとするlistを生成する。

f = open(‘scarlet.txt’, ‘r’)
#f.readlines()でtextをlistにする。
txt_lines = f.readlines()
print(len(txt_lines))
#f.read()でtextをstringにする。
text_lines = f.read()
print(text_lines.count(“\n”))

list内のitemの数をカウントする。

dictionary内最大のvalueを持つkeyを探す。

d = {‘a’: 194, ‘b’: 54, ‘c’:34, ‘d’: 44, ‘e’: 312, ‘full’:31}

ks = d.keys()
best_key_so_far = list(ks)[0]# dから一番最初のkey(str)をアサイン

for k in list(ks):
if d[k] > d[best_key_so_far]:
best_key_so_far = k

print(“key ” + best_key_so_far + ” has the highest value, ” + str(d[best_key_so_far]))

valueはkeyから特定するといい。

dictionary作成→keysでkeyのリスト作成→dictionary[key]でvalue特定

product = “iphone and android phones”

lett_d = {}
for c in product:
lett_d = lett_d.get(c, 0) + 1

print(lett_d)

keys = list(lett_d.keys()) #keyのリストを作ることが重要。
a0 = keys[0]
max_value = a0

for k in keys: #valueはkey経由でdictionaryから参照
if lett_d[k] > lett_d[max_value]:
max_value = k

placement = “Beaches are cool places to visit in spring however the Mackinaw Bridge is near. Most people visit Mackinaw later since the island is a cool place to explore.”

d = {} #dictionary 作る。
for c in placement:
d = d.get(c, 0) + 1
print(d)

keys = list(d.keys()) #valueはkeyから特定する。
a0 = keys[0]#a0使うのいいな。

min_value = keys[0]
for c in keys:
if d <= d[min_value]:
min_value = c

 

course_2_assessment_3

これ大変でした。

sally = “sally sells sea shells by the sea shore”

characters = {}
for i in sally:
if i in characters.keys():
characters[i] = characters[i] + 1
elif i not in characters.keys():
characters[i] = 1
print(characters)
best_char = “s”
for i in characters.keys():
if characters[i] > characters[best_char]:
best_char = i

valueのtotalを得る

 

 

忘れていた完全無欠版

 

 

コメント