字典的常用操作

字典的常用操作

字典元素的获取

获取字典中的元素
[]
get()方法
举例:scores['张三']
举例:scores.get('张三')
  • []取值与使用get()取值的区别

    • []如果字典中不存在指定的key,抛出KeyError异常
  • get()方法取值,如果字典中不存在指定的key,并不会抛出KeyError而是返回None,可以通过参数设置默认的value,以便指定的Key不存在时返回

scores = {'张三': 100, '李四': 98, '王五': 45}
# 第一种方式使用[]
print(scores['张三'])

# 第二种方式get()方法
a = scores.get('张三')
print(a)
b = scores.get('陈六')  # None
print(b)
print(scores.get('麻七', 99))
print(scores.get('麻七', 99))  # 99是在查找'麻七'这个键所对的value不存在时,提供的一个默认值

100
100
None
99
99

key的判断

key的判断
in
指定的key在字典中存在返回true
'张三' in scores
not in
指定的key在字典中不存在返回true
'marry'not in scores
scores = {'张三': 100, '李四': 98, '王五': 45}
print('张三' in scores)
print('张三' not in scores)

True
False

字典元素的删除

del scores[‘张三’]

del scores['张三']
print(scores)
scores.clear()
print(scores)

{'李四': 98, '王五': 45}
{}

字典元素的新增

scores[‘jack’] = 90

scores['陈六'] = 90
print(scores)

{'陈六': 90}

字典元素的修改

scores['陈六'] = 90
print(scores)

scores['陈六'] = 100
print(scores)


{'陈六': 90}
{'陈六': 100}

获取字典视图的三个方法

获取字典视图
keys()
获取字典中所有key
values()
获取字典中所有value
itrms()
获取字典中所有key,value对
scores = {'张三': 100, '李四': 98, '王五': 45}
# 获取字典中所有key
a = scores.keys()
print(a)
print(type(a))
print(list(a))  # 将所有key组成的视图转化成列表

# 获取字典所有value
b = scores.values()
print(b)
print(type(b))
print(list(b))

# 获取所有的键值对
c = scores.items()
print(c)
print(list(c))  # 转换后的列表元素是由元组组成


dict_keys(['张三', '李四', '王五'])
<class 'dict_keys'>
['张三', '李四', '王五']
dict_values([100, 98, 45])
<class 'dict_values'>
[100, 98, 45]
dict_items([('张三', 100), ('李四', 98), ('王五', 45)])
[('张三', 100), ('李四', 98), ('王五', 45)]

字典元素的遍历

scores = {'张三': 100, '李四': 98, '王五': 45}
for item in scores:
    print(item)  # 输出结果为字典当中的键
    print(scores[item], scores.get(item))  # 输出结果为字典当中的值
 
 
张三
100 100
李四
98 98
王五
45 45
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蛰伏GR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值