赞
踩
字典(Dictionary)是Python提供的一种常用的数据结构,由键(key)和值(value)成对组成,键和值中间以冒号:隔开,项之间用逗号隔开,整个字典由大括号{}括起来。
格式如下:
dic = {key1 : value1, key2 : value2 }
字典也被称作关联数组或哈希表。下面是几种常见的字典创建方式:
# 方法1
dic1 = { 'Author' : 'Python当打之年' , 'age' : 99 , 'sex' : '男' }
# 方法2
lst = [('Author', 'Python当打之年'), ('age', 99), ('sex', '男')]
dic2 = dict(lst)
# 方法3
dic3 = dict( Author = 'Python当打之年', age = 99, sex = '男')
# 方法4
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', 99, '男']
dic4 = dict(zip(list1, list2))
字典创建的方式还有很多种,这里不再赘述。
接下来是重点
接下来是重点
接下来是重点
字典由 dict 类代表,可以使用**dir(dict)**来查看该类包含哪些方法,输入命令,可以看到如下输出结果:
methods = dir(dict)
print('methods = ',methods)
methods = ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
字典的方法和属性有很多种,这里我们重点介绍以下11种方法:
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
1、dict.clear()
clear() 用于清空字典中所有元素(键-值对&#x
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。