字典(Dictionary)作为Python中最重要且最常用的数据结构之一,
提供了多种灵活的遍历方式。字典以键值对(key-value pair)形式存储数据,
其遍历方法也围绕键、值或键值对展开。
以下是遍历字典的几种主要方法:
a={'a': '1', 'b': '2', 'c': '3'}
for key in a:
print(key+':'+a[key])
a:1 b:2 c:3
for key in a.keys():
print(key+':'+a[key])
a:1 b:2 c:3
在使用上,for key in a 和 for key in a.keys() :完全等价。
for value in a.values():
print(value)
1 2 3
for kv in a.items():
print(kv)
('a', '1')
('b', '2')
('c', '3')
for key,value in a.items():
print(key+':'+value)
a:1 b:2 c:3
for (key,value) in a.items():
print(key+':'+value)
a:1 b:2 c:3
import pprint
message = 'It was a bright cold day in April, and the clocks werestriking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
{' ': 12,
',': 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}
这一次,当程序运行时,输出看起来更干净,键排过序。
如果字典本身包含嵌套的列表或字典,
pprint.pprint()函数就特别有用。
如果希望得到漂亮打印的文本作为字符串,而不是显示在屏幕上,
那就调用 pprint.pformat()。下面两行代码是等价的:
pprint.pprint(someDictionaryValue)print(pprint.pformat(someDictionaryValue))