python字典

发布时间:2017-11-06 18:07:22编辑:Run阅读(4901)

    所不同的是列表的索引只是从0开始的有序整数,不可重复;而字典的索引实际上在字典里应该叫键,虽然字典中的键和列表中的索引一样是不可重复的,但键是无序的,也就是说字典中的元素是没有顺序而言的,字典中的元素任意排列但不影响字典的使用

    字典的键可以是数字,字符串,列表,元组.....几乎什么都可以,一般用字符串来做键,键与键值用冒号分割,在列表中是通过索引来访问元素,而在字典中是通过键来访问键值,因为字典按“键”来寻值而不同于列表的按“索”寻值,所以字典的操作方法与列表有区别

    首先创建一个字典实验一下,执行命令

    dicttemp = {'name':'Sam','age':'18','sex':'male' }

    这样就建立了一个简单的dicttemp字典,因为字典的键值是无序的,所以插入一个数据无需insert之类的方法,直接定义即可,执行命令:

    dicttemp['college'] = 'tsinghua'

    dicttemp['nation'] = 'china'

    如需添加资料,只需要继续这样添加即可,如果发现资料有误,修改字典,同样也是直接定义,执行命令:

    dicttemp['college'] = 'PKU'

    如果要删除某个元素,可以使用del命令,del命令可以理解为取消分配给变量的内存空间,执行命令:

    del dicttemp['nation']


    del命令不止是可以删除字典元素,类似字典元素,用户定义的变量都可以用del来删除。它可以删除数字变量,字符串变量,列表,元组,字典等等

    字典还有一些独特的操作,以下是字典中最常用的操作:

    1.dict.keys()    返回一个包含字典所有key的列表

    2.dict.values()    返回一个包含字典所有value的列表

    3.dict.items()    返回一个包含所有(键,值)元组的列表

    4.dict.clear()    删除字典中所有的元素

    5.dict.get(key)    返回字典中key所对应的值


    编写一个showdict.py来实验一下:

    showdict.py代码如下:

    # coding: utf-8
    __author__ = 'www.py3study.com'
    class showdict(object):
        '''该类用来展示字典的使用方法'''
        def __init__(self):
            self.spiderman = self.createdict()  #创建字典
            self.insertdict(self.spiderman)     #插入数据
            self.modifydict(self.spiderman)     #修改数据
            self.operationdict(self.spiderman)  #字典操作
            self.deletedict(self.spiderman)     #删除元素
    
        def createdict(self):
            print(u'创建字典:')
            print(u"执行命令spiderman = {'name':'peter parker','sex':'male','nation':'americ','college':'mit'}")
            spiderman = {'name':'peter parker','sex':'male','nation':'americ','college':'mit'}
            self.showdict(spiderman)
            return spiderman
    
        def showdict(self, spiderman):
            print(u"显示字典")
            print(u"spiderman =")
            print(spiderman)
            print('\n')
    
        def insertdict(self, spiderman):
            print(u"字典中添加键age,值为31")
            print(u"执行命令spiderman['age'] = 31")
            spiderman['age'] = 31
            self.showdict(spiderman)
    
        def modifydict(self,spiderman):
            print(u"字典修改键'college'的值为'empire state university'")
            print(u"执行命令 spiderman['college'] = 'empire state university'")
            spiderman['college'] = 'empire state university'
            self.showdict(spiderman)
    
        def operationdict(self,spiderman):
            print(u"字典的其它操作方法")
            print(u"##############################")
            print(u"显示字典所有的键,keylist = spiderman.keys()")
            keylist = spiderman.keys()
            print(u"keylist =")
            print(keylist)
            print('\n')
            print(u"显示字典所有键的值,valuelist = spiderman.values()")
            valuelist = spiderman.values()
            print(u"valuelist =")
            print(valuelist)
            print('\n')
            print(u"显示字典所有键和值的元组,itemlist = spiderman.items()")
            itemlist = spiderman.items()
            print(u"itemlist =")
            print(itemlist)
            print('\n')
            print(u"取字典中键为college的值,college = spiderman.get('college')")
            college = spiderman.get('college')
            print(u"college = {}".format(college))
            print('\n')
    
        def deletedict(self,spiderman):
            print(u"删除字典中键为nation的值")
            print(u"执行命令 del(spiderman['nation'])")
            del(self.spiderman['nation'])
            self.showdict(spiderman)
            print(u"清空字典中所有的值")
            print(u"执行命令 spiderman.clear()")
            self.spiderman.clear()
            self.showdict(spiderman)
            print(u"删除字典")
            print(u"执行命令 del(spiderman)")
            del(spiderman)
            print(u"显示spiderman")
            try:
                self.showdict(spiderman)
            except  NameError:
                print(u"spiderman 未被定义")
    
    if __name__ == '__main__':
        sd = showdict()

    运行结果如下:

    "C:Program Files (x86)python3.6python.exe" D:/python3_study/showdict.py
    创建字典:
    执行命令spiderman = {'name':'peter parker','sex':'male','nation':'americ','college':'mit'}
    显示字典
    spiderman =
    {'name': 'peter parker', 'sex': 'male', 'nation': 'americ', 'college': 'mit'}


    字典中添加键age,值为31
    执行命令spiderman['age'] = 31
    显示字典
    spiderman =
    {'name': 'peter parker', 'sex': 'male', 'nation': 'americ', 'college': 'mit', 'age': 31}


    字典修改键'college'的值为'empire state university'
    执行命令 spiderman['college'] = 'empire state university'
    显示字典
    spiderman =
    {'name': 'peter parker', 'sex': 'male', 'nation': 'americ', 'college': 'empire state university', 'age': 31}


    字典的其它操作方法
    ##############################
    显示字典所有的键,keylist = spiderman.keys()
    keylist =
    dict_keys(['name', 'sex', 'nation', 'college', 'age'])


    显示字典所有键的值,valuelist = spiderman.values()
    valuelist =
    dict_values(['peter parker', 'male', 'americ', 'empire state university', 31])


    显示字典所有键和值的元组,itemlist = spiderman.items()
    itemlist =
    dict_items([('name', 'peter parker'), ('sex', 'male'), ('nation', 'americ'), ('college', 'empire state university'), ('age', 31)])


    取字典中键为college的值,college = spiderman.get('college')
    college = empire state university


    删除字典中键为nation的值
    执行命令 del(spiderman['nation'])
    显示字典
    spiderman =
    {'name': 'peter parker', 'sex': 'male', 'college': 'empire state university', 'age': 31}


    清空字典中所有的值
    执行命令 spiderman.clear()
    显示字典
    spiderman =
    {}


    删除字典
    执行命令 del(spiderman)
    显示spiderman
    spiderman 未被定义


    python的基本变量类型就是这些,其它的类型几乎都是由这些基本类型组合而来(python的数据类型还有None和boolean)

    字典的键和键值可以是任何类型,在没有什么特殊要求的情况下尽可能地使用字符串作为键,如果把键设置的太复杂,那也就失去了字典的意义了

关键字

上一篇: python元组

下一篇: python不得不学的理由!