习题33:字典

发布时间:2017-11-23 14:38:07编辑:Run阅读(5013)

    dict可以让你通过任何东西找到元素,不只是数字,字典可以将一个物件和另外一个东西关联,不管它们的类型是什么,举例说明

    stuff = {'name':'zed','age':'36','height':6*12+2}

    print(stuff['name'])

    zed

    print(stuff['age'])

    36

    print(stuff['height'])

    74

    stuff['city'] = 'wuhan'

    print(stuff['city'])

    wuhan

    你将看到除了通过数字以外,还可以用字符串来从字典中获取stuff,还可以用字符串来往字典中添加元素,当然它支持的不止字符串,还可以做这样的事情(接着上面的例子进行)

    stuff[1] = 'wow'

    stuff[2] = 'neato'

    print(stuff[1])

    wow

    print(stuff[2])

    neato

    print(stuff)

    {'name': 'zed', 'age': '36', 'height': 74, 'city': 'wuhan', 1: 'wow', 2: 'neato'}

    当然了,一个只能放东西进去的字典是没啥意思,所以还有删除物件的方法,使用del这个关键字(接着上面的例子)

    del stuff['city']

    del stuff[1]

    del stuff[2]

    stuff

    {'name': 'zed', 'age': '36', 'height': 74}


    练习代码

    # coding: utf-8
    __author__ = 'www.py3study.com'
    class song(object):
       def __init__(self, lyrics):
           self.lyrics = lyrics

       def sing_me_a_song(self):
           for line in self.lyrics:
               print(line)

    happy_bday = song(["Happy birthday to you","I don't want to get sued","So I'll stop right there"])
    bulls_on_parade = song(["They rally around the family","With pockets full of shells"])

    happy_bday.sing_me_a_song()
    bulls_on_parade.sing_me_a_song()

    你应该看到的效果

    图片.png

    常见问题

    列表和字典有何不同?

    列表是有序排列的一些物件,而字典是将一些物件(keys)对应到另外一些物件(values)的数据结构

    字典能用在哪里?

    各种你需要通过某个值去查看另外一个值的场合,其实可以把字典当作一个'查询表'

    列表能用在哪里?

    列表是专供有序排列的数据使用的,你只要知道索引就能查到对应的值

关键字