Python新手学习(四):字典和结构化数据

本文介绍了Python中字典数据类型及其特性,包括创建、操作(如get(),setdefault())和美化输出(pprint)。并通过国际象棋和井字棋游戏的建模示例展示了如何使用字典进行复杂数据结构的构建和管理。
摘要由CSDN通过智能技术生成

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')))

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值