Python字典常用案例

##########################################################

# 用字典创建九宫格(#字格),字典建模
theBoard = {
    'top-L':'','top-M':'','top-R':'',
    'mid-L':'','mid-M':'','mid-R':'',
    'low-L':'','low-M':'','low-R':'',
}
#print(theBoard)

# 自定义一个函数,画出九宫格(#字格)棋盘
def printBoard(theBoard):
    print(theBoard['top-L'] + ' | ' + theBoard['top-M'] + ' | ' + theBoard['top-R'])
    print('-+--+-')
    print(theBoard['mid-L'] + ' | ' + theBoard['mid-M'] + ' | ' + theBoard['mid-R'])
    print('-+--+-')
    print(theBoard['low-L'] + ' | ' + theBoard['low-M'] + ' | ' + theBoard['low-R'])

#printBoard(theBoard)

# 开始下棋,循环9次
turn = 'X'
for i in range(9):
    printBoard(theBoard)
    print('Turn for ' + turn + '. Move on which space?')
    space = input()
    theBoard[space] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

printBoard(theBoard)


##########################################################

# 字典中嵌套字典
import pprint

allGuests = {
    'Alice':{'apples':5,'pretzels':12},
    'Bob':{'ham sandwiches':3,'apples':2},
    'Carol':{'cups':3,'apple pies':1},
}

pprint.pprint(allGuests)  # 美化字典的输出,显得键-值对更有层次

def totalBrought(allGuests,key):
    numBrought = 0
    for k,v in allGuests.items():
        numBrought += v.get(key,0) # 键不存在与字典时,与该键关联的值给 0
    return numBrought

print('Number of things being brought: ')
print(' - Apples : ' + str(totalBrought(allGuests,'apples')) )
print(' - Pretzels : ' + str(totalBrought(allGuests,'pretzels')) )
print(' - Ham sandwiches : ' + str(totalBrought(allGuests,'ham sandwiches')) )
print(' - Cups : ' + str(totalBrought(allGuests,'cups')) )
print(' - Apple pies : ' + str(totalBrought(allGuests,'apple pies')) )
print(' - Bananas : ' + str(totalBrought(allGuests,'bananas')) )


##########################################################

# 字典运用之好玩游戏的物品分类清单和物品总数

def displayInventory(playList,key):
    amount = 0
    for k,v in playList.items():
        amount = amount + playList.get(key,0)
        return amount

def totalInventory(playList):
    total_amount = 0
    for i in playList.values():
        total_amount += i
    return total_amount

# 定义一个物品清单字典
playList = {'rope':11,'torch':6,'gold coin':42,'dagger':1,'arrow':12,}

# 调用 displayInventory()函数
print('Rope: ' + str(displayInventory(playList,'rope')) )
print('Torch: ' + str(displayInventory(playList,'torch')) )
print('Gold coin: ' + str(displayInventory(playList,'gold coin')) )
print('Dagger: ' + str(displayInventory(playList,'dagger')) )
print('Arrow: ' + str(displayInventory(playList,'arrow')) )
print('Apples: ' + str(displayInventory(playList,'apples')) )

# 调用 totalInventory() 统计总数
print('Total inventory is ' + str(totalInventory(playList)) )


##########################################################

# 列表转字典
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby','dagger',]
# 定义一个空字典,记住:列表的值就是字典的键键键!!!
list = {}

for i in dragonLoot:
    if i in list.keys():
        list[i] += 1
    else:
        list[i] = 1

print(list)


##########################################################

# 字典,列表的灵活运用
stuff = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12,}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby', 'dagger', ]

# 遍历字典键-值对
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k,v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print('Total amount is ' + str(item_total))

# 将列表转成字典
def listTodictory(list):
    # 定义一个空字典,记住:列表的值就是字典的键键键!!!
    dic = {}
    for i in list:
        if i in dic.keys():
            dic[i] += 1
        else:
            dic[i] = 1
    return dic

displayInventory(stuff)  # 遍历字典
print('-------------------------------')
spam = listTodictory(dragonLoot)  # 将列表转换成字典
print(spam)
print('-------------------------------')
displayInventory(spam)  # 将字典 spam 传给遍历字典的函数
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值