字典的增删改查
Posted 爱灰灰的灰灰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典的增删改查相关的知识,希望对你有一定的参考价值。
字典
增
1. 有就覆盖,没有就添加
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} dic[‘sex‘] = ‘LaddyBoy‘ dic[‘name‘] = ‘Alex‘
2. 有就不变,没有就添加
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} dic.setdefault(‘sex‘, ‘Laddyboy‘) dic.setdefault(‘name‘, ‘alex‘) print(dic)
删
1. pop 按照Key删除 , 有返回值,返回删除对应键的值。
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} print(dic.pop(‘age‘)) print(dic.pop(‘age1‘, ‘没有此键...‘)) #如果没有会报错,但是加上值就是返回你写的值 print(dic)
2. clear 清空字典
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} dic.clear() print(dic)
3. pop.item 随机删除,有返回值,返回为元祖,里边是删除的键对值
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} print(dic.popitem()) print(dic)
4. del 删除整个字典
按照键删除
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} del dic[‘name‘] print(dic)
改
1. dic[‘name‘] = ‘Alex‘ 有就覆盖没有就添加
2. update 两个字典的更新
dic = {"name": "jin", "age": 18, "sex": "male"} dic2 = {"name": "alex", "weight": 75} dic2.update(dic) # 将dic里面的所有键值对 覆盖添加到dic2中,dic不变 print(dic) # {‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘} print(dic2) # {‘name‘: ‘jin‘, ‘weight‘: 75, ‘age‘: 18, ‘sex‘: ‘male‘}
查
1. 有就返回值,没有报错
# 1,dic[‘name‘] dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} print(dic[‘name‘])
2. 有就返回值 , 没有返回None
2,dic.get(‘name‘)
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘}print(dic.get(‘name‘)) print(dic.get(‘name1‘)) print(dic.get(‘name1‘, ‘sb没有此键‘))
3. for循环查询
dic.keys(), dic.values(), dic.items() #类似于list但不是list的类型。
# 循环键
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} for key in dic.keys(): print(key)
# 循环值
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} for value in dic.values(): print(value)
# 循环 键 和 值 分别赋值
dic = {‘name‘: ‘老男孩‘, ‘age‘: 56, ‘hobby‘: ‘women‘} for k,v in dic.items(): print(k,v)
以上是关于字典的增删改查的主要内容,如果未能解决你的问题,请参考以下文章