字典(Dictionary)是Python提供的一种常用的数据结构,它用于存放具有映射关系的数据。本期给大家带来Python字典11个方法的全面解析,希望对你有所帮助。
字典由键(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))
字典创建的方式还有很多种,这里不再赘述。
接下来是重点
接下来是重点
接下来是重点
领取免费教程及资料+v:boyin7988 备注Python即可
字典由 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