第五章 字典和结构化数据【Python编程快速上手】

部分及不熟

# 5.1.2 items()方法
spam={'color':'red','age':25}
for i in spam.items():
    print(i)

# ('color', 'red')    (一个元祖)
# ('age', 25)

spam={'color':'red','age':25}
for key,value in spam.items():
    print(key+":"+str(value))
# color:red
# age:25

print(spam.keys())      #dict_keys(['color', 'age'])
print(spam.values())    #dict_values(['red', 25])
print(list(spam.keys()))      #['color', 'age']
print(list(spam.values()))   #['red', 25]

#5.1.4 get('键值',备用值):访问键的值
picnicItems={'apples':5,'cups':2}
print("I'm bring " + str(picnicItems.get('apples',0)) +" apples!")
print("I'm bring " + str(picnicItems.get('watermelon',0)) +" watermelon!")

# 5.1.5 setdefault('键','值'):当字典中没有这个key时候,使用这个值
spam={'color':'red','age':25}
print(spam.setdefault('name','Kim'))        #Kim
print(spam)       #{'color': 'red', 'age': 25, 'name': 'Kim'}

print(spam.setdefault('color','black'))     #red
print(spam)       #{'color': 'red', 'age': 25, 'name': 'Kim'}


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)
# {'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}

# 5.2 美观输出
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)

# {' ': 13,
#  ',': 1,
#  '.': 1,
#  'A': 1,
#  'I': 1,
#  'a': 4,
#  'b': 1,
#  'c': 3,
#  'd': 3,
#  'e': 5,
#  'g': 2,
#  'h': 3,
#  'i': 6,
#  'k': 2,
#  'l': 3,
#  'n': 4,
#  'o': 2,
#  'p': 1,
#  'r': 5,
#  's': 3,
#  't': 6,
#  'w': 2,
#  'y': 1}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值