- keys()、values()、items()返回字典的键、值、键值对
>>> spam = {'color':'red','age':42 }
>>> for k in spam.keys():
print(k)
color
age
>>> for v in spam.values():
print(v)
red
42
>>> for k, v in spam.items():
print('key: ' + k +' values: ' + str(v))
key: color values: red
key: age values: 42
- 检查字典中是否存在键或值
>>> spam = {'name':'zophie','age':7}
>>> 'name' in spam.keys()
True
>>> 'zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False
'color' in spam 是一个简写版本,相当于'color' in spam.keys()
- get()方法
有两个参数:要取得其值的键,以及如果该键不存在时,返回的备用值。避免键不存在时产生KeyError报错。
>>> picnic_items = {'apples':5,'cups':2}
>>> 'I am bringing ' + str(picnic_items.get('cups',0) + ' cups'.)
'I am bringing 2 cups.
>>> 'I am bringing ' + str(picnic_items.get('eggs',0) + ' eggs'.)
'I am bringing 0 eggs.
- setdefault()方法
有两个参数,第一个是要检查的键,第二个是如果键不存在时要设置的值。如果该键确实存在,方法就返回键的值。
>>> spam = {'name':'pooka','age':5}
>>> spam.setdefault('color','black')
black
>>> spam
{'name':'pooka','age':5','color':'black'}
>>> spam.setdefault('color','white')
black
- 计算一个字符串中每个字符出现的次数
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)
import pprint
pprint.pprint(count)
print(pprint.pformat(count))
漂亮打印,导入pprint模块,pprint()和pformat()函数
- 一个小程序,按格式显示一个变化的游戏物品清单。
import pprint
#导入漂亮打印pprint模块
inv = {'gold coin':42,'rope':1} # 原有物品清单
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby'] # 刷一个副本获取的战利品
def addToInventory(inventory,addedItems): # 包含两个参数,原有清单(字典)和新增物品(列表)
"""将新获取的战利品增加到原物品清单中"""
for i in addedItems:
inventory.setdefault(i,0)
inventory[i] += 1
pprint.pprint(inventory) #漂亮打印
return inventory #返回最终清单
spam = addToInventory(inv,dragonLoot)
print(spam)
def displayInventory(inventory):
"""按照格式显示物品清单和物品总数"""
print('Inventory:')
item_total = 0
for k,v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print('Total number of items:' + str(item_total))
displayInventory(spam)
输出
{'dagger': 1, 'gold coin': 45, 'rope': 1, 'ruby': 1}
{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items:48
网友评论