python字典添加元素和刪除元素

1. 添加字典元素函數

方法一:直接添加,給定鍵值對spa

#pycharm
aa = {'人才':60,'英語':'english','adress':'here'}
print(aa) # {'人才': 60, '英語': 'english', 'adress': 'here'}
#添加方法一:根據鍵值對添加
aa['價格'] = 100
print(aa) # {'人才': 60, '英語': 'english', 'adress': 'here', '價格': 100}

方法二:使用update方法code

#添加方法二:使用update方法添加
xx = {'hhh':'gogogo'}
aa.update(xx)
print(aa) # {'人才': 60, '英語': 'english', 'adress': 'here', '價格': 100, 'hhh': 'gogogo'}

2. 刪除字典元素blog

方法一:del函數pycharm

# 刪除方法一:使用del函數
del[aa['adress']]
print(aa) # {'人才': 60, '英語': 'english', '價格': 100, 'hhh': 'gogogo'}

方法二:pop函數class

#刪除方法二:使用pop函數,並返回值
vv = aa.pop('人才')
print(vv) # 60
print(aa) # {'英語': 'english', '價格': 100, 'hhh': 'gogogo'}

方法三:clear函數date

# clear方法,刪除全部
aa.clear()
print(aa) # {},爲空
相關文章