前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 字典(Dictionary) setdefault()方法

Python 字典(Dictionary) setdefault()方法

作者头像
用户7886150
修改2021-01-26 10:29:00
6590
修改2021-01-26 10:29:00
举报
文章被收录于专栏:bit哲学院

参考链接: Python字典setdefault()

描述 Python 字典 setdefault() 函数和 get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值。 

语法 setdefault() 方法语法: 

dict.setdefault(key, default=None) 参数 key – 查找的键值。 default – 键不存在时,设置的默认键值。 返回值 如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。 

实例:统计当前文件夹下的各类文件的总数 

import os

def my_file():

    my_dict = {}

    value = 0

    all_files = os.listdir(os.curdir)

    for each_file in all_files:

        if os.path.isdir(each_file):

            my_dict.setdefault("文件夹",0)

            my_dict["文件夹"]+=1

        else:

            path,ext = os.path.splitext(each_file)

            my_dict.setdefault(ext,0)

            my_dict[ext]+=1

    for  k in my_dict:

        print("{}:{}".format(k,my_dict[k]))

my_file()

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档