Python 字典(一)

用書 PYTHON王者歸來 作者洪錦魁

印出字典內的值

name= {“Nini”:19,”Kiki”:20,”Susan”:60}

school= {“NTY”:100,”JST”:50}

print(name[“Susan”])

print(school[“NTY”])

執行結果

增加字典內元素

name= {“Nini”:19,”Kiki”:20,”Susan”:60}

name[“Pipi”] = 25

print(name)

執行結果

修改字典內元素

name= {“Nini”:19,”Kiki”:20,”Susan”:60,”Pipi”:40}

name[“Pipi”] = 25

print(name)

執行結果

game = {“x”:25 ,”y”:6,”speed”:”fast”}
if game[“speed”]==”slow”:   

game[“x”]+=5

elif game[“speed”]==”fast”:   

game[“x”]+=10

else:   

game[“x”] += 8

print(game)

執行結果

刪除字典元素

game = {“x”:25 ,”y”:6,”speed”:”fast”}

del game[“speed”]

print(game)

執行結果

刪除字典元素

game = {“x”:25 ,”y”:6,”speed”:”fast”}

value = game.pop(“speed”)

print(game)

print(value)

執行結果

隨機刪除字典元素 .popitem()

不知道為什麼這個執行的結果都是刪掉最後一項的

game = {“x”:25 ,”y”:6,”speed”:”fast”,”j”:6}

value = game.popitem()

print(game)

print(value)

執行結果

建立空字典

candy ={}

print(candy)

candy[“applecandy”] =30

print(candy)

執行結果

複製字典

candy ={}

print(candy)

candy[“applecandy”] =30

print(candy)

copycandy = candy.copy()

print(copycandy)

print(id(candy))

print(id(copycandy))

執行結果 ID不同

淺拷貝和深拷貝

  • 淺拷貝

a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

b = a.copy()

print(a)

print(b)b[“x”].append(9)

print(b)

print(a)


print(“**************************************************”)

  • 深拷貝 deepcopy 使用深拷貝不會影響原本的字典

import copy

a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

b = copy.deepcopy(a)

print(a)

print(b)

b[“x”].append(9)

print(a)

print(b)

執行結果

取得元組數量

a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

candy ={}

game = {“x”:25 ,”y”:6,”speed”:”fast”}

print(len(a))

print(len(candy))

print(len(game))

執行結果

驗證元素是否在字典內

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30}

key = input(“Please input a name:”)

value = input(“please input her number:”)
if key in ClassA:   

print(f”{key} is in ClassA,She is number{value}”)

else:   

ClassA[key]=value   

print(ClassA)

執行結果

合併字典

a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30}

a.update(ClassA)

print(a)


a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30,”j”:100}

a.update(ClassA)

print(a)

第二個 “j”存在於’兩個字典,所以會以最後一個值為主

執行結果

Python3.5後的版本

a = {“x”:[25,5] ,”y”:6,”speed”:”fast”,”j”:6}

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30,”j”:100}

d = {**a,**ClassA}

print(d)

執行結果

轉化成字典

name = [[“Kiki”,1],[“Nini”,2],[“Ruru”,3]]

dictname = dict(name)

print(dictname)
ABCD =[(“a”,”b”),(“c”,”d”)]

DictABC = dict(ABCD)

print(DictABC)
NINI = (“ab”,”cd”,”fg”)

DICTNINI = dict(NINI)

print(DICTNINI)

執行結果

第三個例一定只能兩個數而已

ZIP

NINI = dict(zip(“abcde”,range(5)))

print(NINI)
NINO = dict(zip([“100″,”200″,”300”],range(3)))

print(NINO)

執行結果