第5章 字典和结构化数据
5.1 字典数据类型
- “字典”的索引可以使用不同数据类型,不止整数
- 字典的索引被称为“键”,键及其关联的值称为“键-值”对
- 字典输入用{}
【例】
将字典赋给变量myCat,字典的键为'size','color','disposition'。这些键对应的值为'fat','gray','loud'。通过键可访问其值:
字典仍可用整数值作为键(向列表用作下标),但不必从0开始:
5.1.1 字典与列表
- 字典中的表序是不排序的,所以键-值对输入顺序不重要
- 字典中的表序是不排序的,所以不能像列表那样对字典切片
- 不能访问字典中不存在的键
- 字典可用任意值作为键来组织数据
birthdays = {'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4'}
while True:
print('Enter a name(blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday')
date = input()
birthdays[name] = date
print('Birthday database updated.')
5.1.2 key()、values()、和items()方法
- key()、values()、和items()三个字典方法可返回类似列表的值,分别对应于字典的键、字典的值和字典的键-值,但返回的并不是真正的列表,不能被修改,没有append()等方法。但这些数据类型(dict_keys、dict_values、dict_items)可用于for循环
- list()将keys()返回的dict_keys类型值转化为一个对应列表
5.1.3 检查字典中是否存在键或值
5.1.4 get()方法
- 两个参数:要取得的值的键;若该键不存在时,备用值。
5.1.5 setdefault()方法
- 参数1:要检查的键 参数2:若该键不存在时要设置的值
- 返回键的值
#统计message中各字符出现次数
message = 'It was a bright cold day in April,and the clocks were striking thirteen.'
count = {}
for char in message:
count.setdefault(char,0)
count[char] += 1
print(count)
5.2 漂亮打印
import pprint
message = 'It was a bright cold day in April,and the clocks were striking thirteen.'
count = {}
for char in message:
count.setdefault(char,0)
count[char] += 1
pprint.pprint(count)
- 若字典本身包含嵌套的列表或字典,print.print()就很有用
- 希望得到漂亮打印的文本字符串,而不显示。可使用pprint.pformat()
pprint.pprint(count)#等价于print(pprint.pformat(count))
5.3 使用数据结构对真实世界建模
5.3.1 井字棋盘
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'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn +'. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
5.3.2 嵌套的字典和列表
5.4 小结
5.5 习题
5.6 实践项目
5.6.1 好玩游戏的物品清单
def displayInventory(goods):
count = 0
print('Inventory:')
for i,j in goods.items():
print(str(j) + ' ' + i)
count += j
print('Total number of items: ' + str(count))
Goods = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
displayInventory(Goods)
5.6.2 列表到字典的函数,针对好玩游戏物品清单
def addToInventory(inventory,addedItems):
count = 1
for i in range(len(addedItems)):
count = inventory.setdefault(addedItems[i],1)#新物品,值为1,插入
if count != 1:#原有的物品,更改值 +1
inventory[addedItems[i]] += 1
return inventory
def displayInventory(goods):
count = 0
print('Inventory:')
for i,j in goods.items():
print(str(j) + ' ' + i)
count += j
print('Total number of items: ' + str(count))
inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)