spam ={'color':'red','ages':42}for k in spam.keys():print(k, end=' ')print()>>>>> color ages
for v in spam.values():print(v, end=' ')print()>>>>> red 42for k, v in spam.items():print(k, v, end=' ')>>>>> color red ages 42
2、检查字典中是否存在键或值
spam ={'color':'red','ages':42}#'color' in spam 等价于'color' in spam.keys()'color'in spam
>>>>>True'red'in spam.values()>>>>>True
import pprint
message ='it was a bright cold day in April'
count ={}for ch in message:
count.setdefault(ch,0)
count[ch]= count[ch]+1
pprint.pprint(count)>>>>> 输出:
{' ':7,'A':1,'a':3,'b':1,'c':1,'d':2,'g':1,'h':1,'i':4,'l':2,'n':1,'o':1,'p':1,'r':2,'s':1,'t':2,'w':1,'y':1}
theBoard ={'top-L':' ','top-M':' ','top-R':' ','mid-L':' ','mid-M':' ','mid-R':' ','low-L':' ','low-M':' ','low-R':' '}defprintBoard(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 inrange(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)
8、小项目-好玩游戏的物品清单
defdisplay_inventory(inventory):print("Inventory:")
item_total =0for k, v in inventory.items():print(str(v)+' '+ k)
item_total += v
print("Total number of items: "+str(item_total))defaddToInventory(inventory, addedItems):for i in addedItems:
inventory.setdefault(i,0)
inventory[i]+=1
inv ={'gold coin':42,'rope':1}
dragonLoot =['gold coin','dagger','gold coin','gold coin','ruby']
addToInventory(inv, dragonLoot)
display_inventory(inv)>>>>> 输出:
Inventory:45 gold coin
1 rope
1 dagger
1 ruby
Total number of items:48