Python基本資料型別 dict的操作

2021-09-13 14:20:48 字數 1329 閱讀 2256

# 移除指定key的元素-pop()

car_dict =

car_dict.pop("name")

print(car_dict)

# 複製dict-copy()

car_dict1 = car_dict.copy()

print(car_dict1)

# 用於建立乙個新字典,以序列 seq 中元素做字典的鍵,value 為字典所有鍵對應的初始值-fromkeys()

seq = ('google', 'runoob', 'taobao')

c_dict = dict.fromkeys(seq)

print("新字典為 : %s" % str(c_dict))

c_dict = dict.fromkeys(seq, 10)

print("新字典為 : %s" % str(c_dict))

# 指定key獲取value-get()

print(car_dict.get("name2"))

# 以列表返回可遍歷的(鍵, 值) 元組陣列-item()

car_item = car_dict.items()

print(car_item)

d =

result =

for k, v in d.items():

print(result)

# 返回乙個可迭代物件,可以使用 list()來轉換為列表-keys()

print(car_dict.keys())

print(list(car_dict.keys()))

# 隨機刪除item,不建議使用-popitem()

car_dict.popitem()

print(car_dict)

# 和get()方法類似, 如果鍵不已經存在於字典中,將會新增鍵並將值設為預設值

print(car_dict.setdefault("name2", none))

# 把字典引數 dict2 的 key/value(鍵/值) 對更新到字典 dict 裡-update()

car1_dict =

car_dict.update(car1_dict)

print(car_dict)

# 返回乙個迭代器,可以使用 list() 來轉換為列表,列表為字典中的所有值-values()

print(car_dict.values())

print(list(car_dict.values()))

# 清空dict-clear()

car_dict.clear()

print(car_dict)

python基本資料型別

物件是python中最基本的概念,python中資料以物件的形式出現 無論是python提供的內建物件,還是使用python或是像c擴充套件庫這樣的擴充套件語言工具建立的物件。物件時記憶體中的一部分,包括數值和相關操作的集合。python程式可以分解成模組 語句 表示式以及物件,如下 1 程式由模組...

Python基本資料型別

1 python中一切都是物件。2 每乙個資料都有乙個id標示,用id 可以檢視。也可以用type檢視是什麼型別。3 常用的資料型別 int 整型 數字 boole true 值 賦值,要用大寫 a true string 字串 也稱作序列。list 列表 tuple 元組 dict 字典 set ...

Python基本資料型別

python內建許多資料基本型別。資料型別dt 表示形式 int整形如 1,0,1,float 浮點型如 1.1,0.0,1.1,str字串如 單引號或雙引號括起來的形式 hello python list 列表如 1,2 巢狀列表 1,2,3 tuple 元組如 1,2 set無序列表如 comp...