Python学习笔记(四) 关于dictionary遍历

在python中,提供了一种可以快速查找的dictionary数据类型,与tuple和list大同小异,但是用起来却很方便:

d={0:'zero',3:'a tuple', 'two':[1,2,3],'one':1}

>>> for c in d.iterkeys():
...     print c;
...
0
3
two
one

>>> for c in d.iterkeys():
... print d[c]
...zero
a tuple
[1, 2, 3]
1

>>> for c in d.iterkeys():
...     print c,d[c];
...
0 zero
3 a tuple
two [1, 2, 3]
one 1

>>> for c in d.itervalues():
...     print c
...
zero
a tuple
[1, 2, 3]
1

 
  
>>> for c in d.iteritems():
...     print c;
...
(0, 'zero')
(3, 'a tuple')
('two', [1, 2, 3])
('one', 1)
>>> for k,v in d.iteritems():
...     print 'd[',k,']=',v
...
d[ 0 ]= zero
d[ 3 ]= a tuple
d[ two ]= [1, 2, 3]
d[ one ]= 1

三种遍历方式分别为iterkeys(),itervalues(),iteritems()

d.iterkeys()返回值为dictionary的键值,同时也可以以类似C语言中数组的形式返回函数的值

d.itervalues()返回值仅为dictionary的值

d.iteritems()允许遍历dictionary的全部值,一次遍历即为全体值。






你可能感兴趣的:(python基础编程)