Python 字典操作

2021-10-02 17:37:00 字數 2867 閱讀 1808

#字典:

#1.定義 : 字典裡的資料是以鍵值對出現的,字典資料跟順序沒有關係,即字典不支援下標操作

#無論資料(值)怎麼變化,只要根據鍵來查詢就能找到資料

#特點 : 大括號,鍵值對形式出現,用逗號隔開

#字典是可變型別

#1.1建立字典

#建立有資料的字典 :

dict1 =

print(dict1) #輸出

print(type(dict1)) #輸出 #建立空字典

#直接用大括號

nulldict1 = {}

print(type(nulldict1)) #輸出 #使用函式 dict()建立空字典

nulldict2 = dict()

print(type(nulldict2)) #輸出

#2.字典的常用操作

#2.1增/改

# 字典序列[key] = 值

# 如果key存在,則修改這個key的值,如果key不存在,則新增

dict1 =

print(dict1) #輸出

dict1["name"] = 'liu'

print(dict1) #輸出

dict1["country"] = 'china'

print(dict1) #輸出

#print(type(dict["name"])) #報錯 typeerror: 'type' object is not subscriptable

#2.2 刪

#2.2.1 del() / del : 刪除字典或刪除字典中指定鍵值對

print(dict1) #輸出

del dict1['gender']

print(dict1) #輸出

del(dict1['country'])#輸出

print(dict1)

#del dict1 #刪除整個dict1

#注意,當刪除不存在的key時,會報錯 keyerror: 'counter'

#2.2.2 clear()

dict1.clear()

print(dict1) #輸出 {}

dict1 = 

#3.查詢

#3.1 key值查詢

print(dict1['name']) #輸出 willow

#print(dict1['country']) #當字典沒有該key時,報錯 keyerror: 'country'

#3.2 get()函式

#語法 字典序列.get(key, 預設值)

#注意 : 如果當前查詢的key不存在,則返回第二個引數(預設值),如果省略第二個引數,則返回none

print(dict1.get('name', 'liu')) #輸出 willow

print(dict1.get('country', 'china')) #輸出 china

print(dict1.get('id')) #輸出 none

#3.3 keys() 函式

#返回字典中的key

print(dict1.keys()) #輸出 dict_keys(['name', 'age', 'gender'])

print(type(dict1.keys())) #輸出 #3.4 values()函式

#返回字典中的values

print(dict1.values()) #輸出 dict_values(['willow', 20, 'man']),返回可迭代物件

print(type(dict1.values())) #輸出 #3.5 items() 函式

#返回乙個可迭代物件,鍵值對以元組(包含兩個元素,乙個key,乙個value)的形式返回

print(dict1.items()) #輸出 dict_items([('name', 'willow'), ('age', 20), ('gender', 'man')])

print(type(dict1.items())) #輸出

#4字典的迴圈遍歷

#4.1 遍歷字典的key

dict1 =

for keys in dict1.keys():

print(keys)

'''輸出

name

agegender

country

'''#4.2 遍歷字典的value

for value in dict1.values():

print(value)

'''輸出

willow

30man

china

'''#4.3 遍歷字典的元素

for item in dict1.items():

print(item)

'''輸出

('name', 'willow')

('age', 30)

('gender', 'man')

('country', 'china')

'''#4.4 遍歷字典的鍵值對,指將得到的資料經行拆包動作

for key , value in dict1.items():

print(f'key:, value:')

'''輸出

key:name, value:willow

key:age, value:30

key:gender, value:man

key:country, value:china

'''

python操作字典 Python 字典操作高階

學習了 python 基本的字典操作後,學習這些高階操作,讓寫出的 更加優雅簡潔和 pythonic 與字典值有關的計算 問題想對字典的值進行相關計算,例如找出字典裡對應值最大 最小 的項。解決方案一 假設要從字典 中找出值最小的項,可以這樣做 d min zip d.values d.keys 2...

python 字典操作

python 語法之字典 2009 10 21 磁針石 xurongzhong gmail.com 部落格 oychw.cublog.cn python essential reference 4th edition 2009 beginning python from novice to prof...

python 字典操作

1 什麼是字典?字典是python語言中唯一的對映型別。對映型別物件裡雜湊值 鍵,key 和指向的物件 值,value 是一對多的的關係,通常被認為是可變的雜湊表。字典物件是可變的,它是乙個容器型別,能儲存任意個數的python物件,其中也可包括其他容器型別。字典型別與序列型別的區別 1.訪問和訪問...