《Python编程快速上手,让繁锁工作自动化》笔记 第5章--字典和结构化数据

5.1 字典数据类型

      字典是许多值的集合,索引可以使用许多不同数据类型,以“键-值”对形式表现。

       >>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

      字典中的表项是不排序的,也不能切片,列表的表项的顺序很重要。

      可以用关键字in, 查看内容是否作为键存在于字典中,例如: ‘size' in myCat   返回True  ’fat' in myCat 返回False

      可以用方括号访问关联的值。 myCat['size']   返回 ‘fat'

      keys()、values()和items()方法,返回的值不是真正的列表,不能被修改,数据类型为(dict_keys、dict_values和dict_items),可用于for循环


>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():   #遍历值
        print(v)
 
red
42

>>> for k in spam.keys():       #遍历键
        print(k)
 
color
age
>>> for i in spam.items():    #遍历键-值
        print(i)
 
('color', 'red')
('age', 42)

>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
        print('Key: ' + k + ' Value: ' + str(v))
 
Key: age Value: 42
Key: color Value: red


检查字典中是否存在键或值 :  有in 和  not in 操作符检查值是否存在于列表中。


>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False


get()方法:取得键值,有2个参数,要取得其值的键,以及如果键不存的在备用值。


>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'


setdefault()方法: 为字典中某个键设置一个默认值,当该键没有任何值时使用它。

修改字典键值: spam['age'] = 10

 

5.2  漂亮打印

       在程序中导入pprint模块,就可以使用pprint()和pfromat()函数,实现格式打印。

      import pprint

      pprint.pprint(count)

 

 

5.3  使用数据结构对真实世界建模

          例如一个九格宫棋盘


theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
            'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
            'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
    print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
    print('-+-+-')
    print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
    print('-+-+-')
    print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)


对复杂的事物建模时,列表适用于包含一组有序的值,字典适合包含关联的键与值。


allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
             'Bob': {'ham sandwiches': 3, 'apples': 2},
             'Carol': {'cups': 3, 'apple pies': 1}}
 
def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item, 0)
    return numBrought
 
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))  


字典是有用的,因为可以把一些项(键)映射到另一些项(值),它不像列表,只包含一系列有序的值。字典中的值是通过方
括号访问的,像列表一样。字典不是只能使用整数下标,而是可以用各种数据类型作为键:整型、浮点型、字符串或元组。通过将程序中的值组织成数据结构

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值