##########################################################
# 字典
birthdays = {'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4',}
print(birthdays)
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays.keys():
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday? ')
add_birthday = input()
birthdays[name] = add_birthday
print('Birthday database updates')
print(birthdays)
##########################################################
# 遍历字典键/值/键值对
birthdays = {'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4',}
print('*******keys*********')
for keys in birthdays.keys():
print(keys)
print('*******values*********')
for values in birthdays.values():
print(values)
print('*******1:keys and values *********')
for i in birthdays.items():
print(i) # 元组
print(list(i)) # 列表
print('******:2: keys and values*********')
for k,v in birthdays.items():
print('Key: ' + k + ' ,Value: ' + v)
##########################################################
# 字典的 get() 方法
picnicItems = {'apples': 5, 'cups': 2, }
get1 = picnicItems.get('apples',0)
get2 = picnicItems.get('bananas',0)
print (get1)
print(get2)
##########################################################
# 字典的 setdefault() 方法
spam = {'name':'Pooka','age':5,}
print(spam)
spam.setdefault('color','black') # 键 color不存在,所以给默认值 black
print(spam)
spam.setdefault('color','white') # 与 color关联的值在上面已经给了 black,因此这里的值 white不起作用
print(spam)
##########################################################
# 统计字符串里每个字符出现次数
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] += 1
print(count) # 普通打印,写在一行,看起来不太整洁
pprint.pprint(count) # pprint.pprint() 函数接受一个字典作为实际参数,按照字典的键升序排序
print('*************************')
print(pprint.pformat(count)) # 等价于 pprint.pprint(count)
##########################################################