python基础篇--Dict(字典)

骑猪看日落 2022-07-13 14:53 427阅读 0赞

dict(字典)

特点:由键和对应值成对组成,字典也被称作关联数组或哈希表

标识:{}

例子:dict2 = {‘dong’:123, ‘you’:456, ‘yuan’:789}

访问字典:

  1. dict2 = {'dong': 123, 'you': 456, 'yuan': 789}
  2. print dict2['dong']
  3. print dict2['you']
  4. # 输出结果
  5. # 123
  6. # 456

修改字典:

  1. dict2 = {'dong': 123, 'you': 456, 'yuan': 789}
  2. print dict2['dong']
  3. dict2['dong'] = '111'
  4. print dict2['dong']
  5. # 输出结果
  6. # 123
  7. # 111

删除字典:

  1. dict2 = {'dong': 123, 'you': 456, 'yuan': 789}
  2. del dict2['dong']
  3. print dict2
  4. dict2.clear()
  5. print dict2
  6. del dict2
  7. print dict2
  8. # 输出结果
  9. # {'you': 456, 'yuan': 789}
  10. # {}
  11. #del dict2 已经删除了dict2,所以dict2没有定义错误
  12. # print dict2
  13. # NameError: name 'dict2' is not defined

字典特性:

(1)字典值可以没有限制地取任何python对象,但是不允许同一个键出现两次,同一个键被赋值两次时,前一个值会别后一个值所覆盖。

  1. dict2 = {'dong': 123, 'you': 456, 'yuan': 789}
  2. dict2['dong'] = '111'
  3. dict2['dong'] = '222'
  4. print dict2['dong']
  5. # 输出结果
  6. # 222

(2)键必须为不可变,所以可以用数字,字符串或元组,但是不能够用列表

  1. dict2 = {['dong']: '111', 'you': '222'}
  2. l = ['dong']
  3. print dict2[l]
  4. # 输出结果
  5. # dict2 = {['dong']: '111', 'you': '222'}
  6. # TypeError: unhashable type: 'list'

内置函数:

cmp(dict2, dict3):比较两个字典

len(dict2):字典元素个数(键的个数)

str(dict2):转化成字符串

type(variable):

字典方法:

dict2.clear(): 删除字典内所有元素

dict2.copy(): 返回一个字典的浅复制(跟原来的dict2共同引用元素的内存地址)

dict2.fromkeys(): 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

dict2.get(key, default=None):

dict2.has_key(key): 如果键在字典里面返回True,否则返回False

dict2.items(): 以列表返回可遍历的(键, 值) 元组数组

dict2.keys(): :以列表返回一个字典所有的键

dict2.setdefault(key, default=None): 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default

dict2.update(dict3): 把字典dict3的键/值对更新到dict里

dict2.values(): 以列表返回字典中的所有值

发表评论

表情:
评论列表 (有 0 条评论,427人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pythondict字典

    字典是一系列由键(key)和值(value)配对组成的元素的集合,在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个implementation