部分及不熟
# 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}