Python字典的用法

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

# 字典
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)


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值