python3 刪除字典元素

2021-09-24 08:44:55 字數 670 閱讀 1925

python不關心鍵-值對的新增順序,而只關心鍵和值之間的關聯關係。

pop()刪除給定健對應的值,如:dict.pop(key) ,key不能為空

clear()清空字典內容,dict.clear()

popitem()隨機刪除字典內容, dict.popitem()

使用del語句刪除字典的鍵-值對

**:

fruits = 

print(fruits)

current_fruit = fruits.pop('p')

print(current_fruit)

print(fruits)

current_fruit = fruits.pop('w')

print(current_fruit)

print(fruits)

del fruits['a']

print(fruits)

current_fruit = fruits.popitem()

print(current_fruit)

print(fruits)

fruits.clear()

print(fruits)

輸出:pear

watermelon

('b', 'banana')

{}

字典怎麼增加元素 python3基礎之字典

字典和列表一樣,也是python內建的一種資料結構。字典的結構如下圖 列表用中括號把元素包起來,而字典是用大括號 把元素包起來,只不過字典的每乙個元素都包含鍵和值兩部分。鍵和值是一一對應的關係。畫個難看的圖表示一下 字典中的鍵要求是唯一的,這個很好理解,如果有兩個鍵是一樣的,那我怎麼知道要找到是哪個...

Python3 教程 字典

字典是另一種可變容器模型,且可儲存任意型別物件 字典的每個鍵值 key value 對用冒號 分割,每個鍵值對之間用逗號 分割,整個字典包括在花括號 中 格式如下所示 d dict print dict name dict name print dict age dict age dict name...

python3字典遍歷 python3字典遍歷

python版本 python3.7 info infog.get name 得到字典info中name的值 info.keys 得到字典info中所有的鍵,結果是乙個物件 dict keys name age 需要注意在python2中該操作得到的是乙個列表 遍歷key for temp in i...