字典数据类型
>>> myCat = {'size':'fat','color':'gray','disposition':'loud'}
>>> myCat['size']
'fat'
>>> '颜色是' + myCat['color'] + 'fur.'
'颜色是grayfur.'
>>> # 字典仍然可以用整数作为键,就像列表使用整数值作为下标一样。可以是任何数字
>>> spam = {123:'geuus',233:'The Answer'}
>>> spam[123]
'geuus'
字典与列表
>>> spam = ['cat','dogs','moose']
>>> bacon = ['dogs','moose','cats']
>>> spam == bacon
False
>>> eggs = {'name':'zophie','species':'cat','age':'8'}
>>> ham = {'species':'cat','age':'8','name':'zophie'}
>>> eggs == ham
True
birthdays = {'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4'}
while True:
print('输入 名称 : (查询生日)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + '的生日是 ' + name)
else:
print('我没有他的生日的信息 ' + name)
print('他们的生日是什么')
bday = input()
birthdays[name] = bday
print('生日数据更新')
keys()、values()和items()方法
>>> spam = {'color':'red','age':42}
>>> for k in spam.keys():
... print(k)
...
color
age
>>> for v in spam.values():
... print(v)
...
red
42
>>> for i in spam.items():
... print(i)
...
('color', 'red')
('age', 42)
>>> spam = {'color':'red','age':42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
>>> spam = {'color':'red','age':42}
>>> for k,v in spam.items():
... print('键是' + k + '值是' + str(v))
...
键是color值是red
键是age值是42
检查字典中是否存在键或值
>>> spam = {'name':'Zophie','age':7}
>>> 'name' in spam.keys()
True
>>> 'Zophie'
'Zophie'
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False
get()方法
>>> picnicItems = {'apples':5,'cups':2}
>>> 'I am bringing' + str(picnicItems.get('cups',0)) + 'cups.'
'I am bringing2cups.'
>>> 'I am bringing' + str(picnicItems.get('color',0)) + 'color.'
'I am bringing0color.'
>>> # 不使用get()代码就会产生一个错误消息
>>> picnicItems = {'apples':5,'cups':2}
>>> 'I am bringing' + str(picnicItems['color']) + ' color'
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'color'
setdefault()方法
>>> spam = {'name':'Poola','age':5}
>>> spam.setdefault('color','black')
'black'
>>> spam
{'name': 'Poola', 'color': 'black', 'age': 5}
>>> spam.setdefault('color','white')
'black'
>>> spam
{'name': 'Poola', 'color': 'black', 'age': 5}
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)
print('-' *50)
for character in message:
count.setdefault(character,0)
count[character] = count[character] + 1
print(count)
漂亮打印
import pprint
message = 'It was a bright cold day in April, and the clocks were striking'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
井字棋盘
theBoard = {'top-L': ' O', 'top-M': 'O ', 'top-R': 'O ',
'mid-L': ' ', 'mid-M': ' X', 'mid-R': ' X',
'low-L': ' ', 'low-M': ' ', 'low-R': 'X '}
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'])
printBoard(theBoard)
打印出棋盘,获取当前棋手的想法,相应地更新棋盘,然后改变当前棋手。
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)
嵌套的字典和列表
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')))