5.字典和结构化数据
1)字典数据类型
字典实际就是“键值对组合”,{‘kkk’:’vvv’,‘kkk1’:’vvv1’},类似于Map
字典和列表的区分,字典项不排序,没有序号下标的概念。因为输入时顺序不同但键值对相同的字典结构是相等的。
字典不排序,也不能进行切片。
测试程序 test_501.py
birthdays = {'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4'}
while True:
print ('Enter a name:(balnk 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?')
bday = input()
birthdays[name] = bday
print('Birthday database update.')
keys()、values()和item()方法,可以检查键和值是否存在。
get()方法,取对应键的值,并且在不存在时可以设置备用值。
setdefault()方法,设置缺省值。如果不存在该键,则设置缺省值,存在则不设置。
测试程序 test_502.py 用于对文章中出现的字母计数。
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character,0)
count[character] = count[character] + 1
print(count)
2)美观的输出 pprint 可以对键进行排序显示
测试程序 test_503.py
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character,0)
count[character] = count[character] + 1
#pprint.pprint(count)
print(pprint.pformat(count))
3)使用数据结构对真实世界建模
国际象棋的数据建模
井字棋盘。
测试程序 test_504.py
#theBoard = {'top-L':'O','top-M':'O','top-R':'O',
# 'mid-L':'X','mid-M':'X','mid-R':' ',
# 'low-L':' ','low-M':' ','low-R':'X'}
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)
嵌套的字典和列表
测试程序test_505.py
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')))