【例】
将字典赋给变量myCat,字典的键为'size','color','disposition'。这些键对应的值为'fat','gray','loud'。通过键可访问其值:
字典仍可用整数值作为键(向列表用作下标),但不必从0开始:
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.')
#统计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)
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)
pprint.pprint(count)#等价于print(pprint.pformat(count))
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)
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)
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)