Python 字典、字典容器类

#!/usr/bin/env python
#-*- coding:utf-8 -*-

if __name__ == "__main__":
  dic = {}
  print "字典是一个类:"
  print "dir(dict):",dir(dict)
  '''
  字典是一个类:
  dir(dict): ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__',
              '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__',
              '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
              '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
              'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
              'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
  '''
  print ""
  print "定义一个字典:"
  dic = {'k1':123,'k2':'abc','k3':['the value is list'],'k4':{'k1':'the value is dict'},\
         1:'the key is num',\
         ('key is tup',1):('value is tup',), \
         ## 键唯一,如果如下重复,以最后一个为准
         'name':'Larry',\
         'name':'Dorry',\
         # 只有不可变对象才可以作为键,而值可以是任意
         # True:"boolean cannot be key"\
         # ['! key cannot be list']:'error!'\
         # {'k':'key cannot be dict'}:'error!'\
         }
  print "dic is:",dic
  '''
  输出:dic is: {'k3': ['the value is list'], 'k2': 'abc', 'k1': 123, 1: 'the key is num', 'name': 'Dorry', \
       'k4': {'k1': 'the value is dict'}, ('key is tup', 1): ('value is tup',)}
  '''
  print ""
  print "字典的元素是无序的,所以不能通过下标索引,但可以通过键值"
  print "dic['k3']:", dic['k3']
  print "dic['k4']:", dic['k4']
  print "dic[1] 并不代表下标为1的元素,而是指键为1 的键值"
  print "dic[1]:", dic[1]
  print "dic[('key is tup',1)]:", dic[('key is tup',1)]
  print ""
  print "增,改,删:"
  #可以这样添加字典的键值对,或修改键的值,被修改的值的类型可以和原来的类型不同
  dic['k5'] = 'add key 5'
  dic['k1'] = '123'
  print "删除k3 键值对('k3': ['the value is list'])"
  del dic['k3']
  print dic
  print "清空字典dic中的所有键值对"
  dic.clear()
  print dic
  #print "删除字典dic:(会释放dic,如再会因为没有定义dic 引发一个错误)"
  #del dic
  #print dic
  '''
  输出:
  字典的元素是无序的,所以不能通过下标索引,但可以通过键值
  dic['k3']: ['the value is list']
  dic['k4']: {'k1': 'the value is dict'}
  dic[1] 并不代表下标为1的元素,而是指键为1 的键值
  dic[1]: the key is num
  dic[('key is tup',1)]: ('value is tup',)
  增,改,删:
  删除k3 键值对('k3': ['the value is list'])
  {'k2': 'abc', 'k1': '123', 1: 'the key is num', 'name': 'Dorry', 'k5': 'add key 5', 'k4': {'k1': 'the value is dict'}, ('key is tup', 1): ('value is tup',)}
  清空字典dic中的所有键值对
  {}

  Traceback (most recent call last):
  File "/home/zhanglu/PycharmProjects/20180409/test_dic.py", line 36, in 
    print dic
  NameError: name 'dic' is not defined
  '''

  print "字典的遍历:"
  dic = {'k1':123,'k2':'abc','k3':['the value is list'],'k4':{'k1':'the value is dict'}}
  for k in dic:
    print k,":",dic[k]
  '''
  输出:
  字典的遍历:
  k3 : ['the value is list']
  k2 : abc
  k1 : 123
  k4 : {'k1': 'the value is dict'}
  '''
  print ""
  print "=============================================================="
  ## 通过dir(dict)可以看到字典类有很多内部方法,以下调几个说一下
  print "dict.fromkeys([键序列],默认值(默认None))"
  dic2 = dict.fromkeys(['name','age','job'])
  print dic2
  dic2 = dict.fromkeys(['name','age','job'],'')
  print dic2
  '''
  输出:
  dict.fromkeys([键序列],默认值(默认None))
  {'job': None, 'age': None, 'name': None}
  {'job': '', 'age': '', 'name': ''}
  '''
  print ""
  print "dict.get(key,default=None)返回指定键的值,如果值不在字典中返回default值(默认None)"
  ##以前不知道get方法,每回怕程序崩,都先判断一次 if key in dict
  dic2 = {'job': 'techer', 'age':24, 'name': 'Larry'}
  print "job:",dic2.get('job')
  print "sex:", dic2.get('sex','male')
  print 'addr:',dic2.get('addr')
  print "如果没有键,添加键并设默认值:(如果已存在键,则不改变原值)"
  print "dic2:",dic2
  dic2.setdefault('sex','male')
  dic2.setdefault('job', 'student')  #不变
  print "dic2",dic2
  '''
  输出:
  dict.get(key,default=None)返回指定键的值,如果值不在字典中返回default值(默认None)
  job: techer
  sex: male
  addr: None
  '''
  print ""
  print "以列表返回可遍历的(键, 值) 元组数组:",dic2.items()
  print "以列表返回一个字典所有的键:",dic2.keys()
  print "把字典dic2的键/值对更新到dic1里"
  dic1 = {'job': 'baby', 'age':3, 'name': 'Larry'}
  dic1.update(dic2)
  print "dic1:",dic1
  '''
  输出:
  以列表返回可遍历的(键, 值) 元组数组: [('job', 'techer'), ('sex', 'male'), ('age', 24), ('name', 'Larry')]
   以列表返回一个字典所有的键: ['job', 'sex', 'age', 'name']
   把字典dic2的键/值对更新到dic1里
   dic1: {'job': 'techer', 'name': 'Larry', 'age': 24, 'sex': 'male'}
  '''

你可能感兴趣的:(python语言基础)