>>> from env_helper import info; info()
待更新
5.5. Python字典遍历的几种方法¶
5.5.1. (1)遍历key值¶
>>> a={'a': '1', 'b': '2', 'c': '3'}
>>> for key in a:
>>> print(key+':'+a[key])
b:2
c:3
a:1
>>> for key in a.keys():
>>> print(key+':'+a[key])
b:2
c:3
a:1
在使用上,for key in a和 for key in a.keys():完全等价。
5.5.2. (2)遍历value值¶
>>> for value in a.values():
>>> print(value)
2
3
1
5.5.3. (3)遍历字典项¶
>>> for kv in a.items():
>>> print(kv)
('b', '2')
('c', '3')
('a', '1')
5.5.4. (4)遍历字典健值¶
>>> for key,value in a.items():
>>> print(key+':'+value)
b:2
c:3
a:1
>>> for (key,value) in a.items():
>>> print(key+':'+value)
b:2
c:3
a:1
漂亮打印¶
如果程序中导入 pprint
模块,就可以使用 pprint()
和 pformat()
函数,它们将“漂亮打印”一个字典的字。如果想要字典中表项的显示比
print()
的输出结果更干净,这就有用了。修改前面的
characterCount.py
程序,将它保存为 prettyCharacterCount.py
。
>>> 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))