{1: ‘a‘, 2: ‘b‘} >>> for k in d: print(k) 1 2 >>> for k in d.keys(): print(k) 1 2 >>> for k in d: print(d[k]) a b >>> for item in d.items(): print(item) (1, ‘a‘) (2, ‘b‘) >>> for k,v in d.items(): print(k,v) 1 a 2 b >>>
六、有序字典OrderedDict
有序字典可以记录元素插入的顺序,打印的时候也是按照这个顺序输出打印
举例:
>>> from collections import OrderedDict
>>> import random
>>> d = {‘banana‘:3,‘apple‘:4,‘pear‘:1,‘orange‘:2}