当前位置:   article > 正文

Python 字典用法详解(超全)

python 字典

字典(Dictionary)是Python提供的一种常用的数据结构,由键(key)和值(value)成对组成,键和值中间以冒号:隔开,项之间用逗号隔开,整个字典由大括号{}括起来

格式如下:

dic = {key1 : value1, key2 : value2 }
  • 1

字典也被称作关联数组或哈希表。下面是几种常见的字典创建方式:

# 方法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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

字典创建的方式还有很多种,这里不再赘述。

接下来是重点

接下来是重点

接下来是重点

字典由 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']
  • 1
  • 2
  • 3
  • 4

字典的方法和属性有很多种,这里我们重点介绍以下11种方法

['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
  • 1

1、dict.clear()

clear() 用于清空字典中所有元素(键-值对&#x

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/655154
推荐阅读
相关标签
  

闽ICP备14008679号