栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第五章 字典和结构化数据【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}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977379.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号