iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
自我挑戰組

新手也想開始認識機器學習系列 第 7

Day 7 python字典

今天我們要介紹的是python的字典,所謂的字典就是指將元素用{}包住並且元素是由一個鍵(key)配上一個值(value)所組合而成的,像是我們平常用的字典。

字典(dictionary)

以下我們介紹幾個間單的字典例子。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(data)
print(data1)

首先我們先宣告字典的變數,可以使用{}來宣告。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(type(data))
print(type(data1))

可以使用type()去查詢變數的型態。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
for i in data:
    print(i)
for j in data1:
    print(j)

可以使用FOR迴圈來抓取字典裡面的key,可以看得抓出來資料是key而不是value。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
for i in data:
    if i == "orange":
        print(i)
for j in data1:
    if j == "k":
        print(j)

可以使用條件判斷去抓取想要的資料,但資料抓取的是key。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(data["watermelon"])
print(data1['b'])

由於字典是由一個key配一個value而如果想查詢某個key對應哪個value就可以使用上述方法去抓取value的資料。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
for i in data:
    print(data[i])
for j in data1:
    print(data1[j])

如果要用FOR迴圈查詢所有的value則可使用這種方式抓取。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
for i in data:
    if data[i] >= 60:
        print(data[i])
for j in data1:
    if data1[j] >= 20:
        print(data1[j])

而如果要以value做條件判斷則可以使用此種方法去做判斷。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(data)
print(data1)
data["mango"] = 90
data1["y"] = 25
print(data)
print(data1)

對字典做增加的動做只需要將變數後面加上想要加的key且key的value就可以增加進字典裡。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(data)
print(data1)
del data["apple"] 
del data1["z"] 
print(data)
print(data1)

如果要對字典做刪除的動作,可以使用此方法將字典裡的key跟value做刪除的動作。

data = {"apple":50,"banana":40,"watermelon":78,"orange":43,"grape":63}
data1 = {"a":1,
        "b":2,
        "d":4,
        "z":26,
        "k":11}
print(data)
print(data1)
data["apple"] = 21 
data1["z"] = 16
print(data)
print(data1)

如果只是單純的修改value,可以使用此種方法將value做修改而不用刪除重新增加。

以上就是簡單的python字典的介紹,明天我們將介紹python的類別。


上一篇
Day 6 python集合
下一篇
Day 8 python類別
系列文
新手也想開始認識機器學習30

尚未有邦友留言

立即登入留言