Python入门题047:dict「key」和dict.get(key) 的区别

题目:

比较 dict[key] 和 dict.get(key) 的用法和区别。

#python #字典dict

视频教程:

Python入门题047:dict[key] 和 dict.get(key) 的区别

代码1:

stat = {'a': 1}

print(stat['a'])

# 直接拿 b 会出错
# print(stat['b'])

# 通过 get 拿不会出错
print(stat.get('b'))


代码2:

stat = {}
colors = ['红', '蓝', '红']
for color in colors:
    # 旧的写法:
    if color not in stat:
        stat[color] = 0
    stat[color] += 1

print(stat)

stat = {}
colors = ['红', '蓝', '红']
for color in colors:
    # 新的写法:
    # get 既避免了 key 不存在导致的错误,又可以提供默认值
    stat[color] = stat.get(color, 0) + 1

print(stat)

展开阅读全文

页面更新:2024-03-14

标签:入门   区别   写法   视频教程   字典   题目   错误   代码   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top