accessing keys in dict

Dustan DustanGroups at gmail.com
Sat Aug 25 15:05:07 EDT 2007


On Aug 25, 7:41 am, Lawrence D'Oliveiro <l... at geek-
central.gen.new_zealand> wrote:
> In message <1187143106.021325.104... at l22g2000prc.googlegroups.com>,
>
> james_027 wrote:
> > is there any difference between ..
>
> > for key in a_dict:
>
> > from
>
> > for key in a_dict.keys():
>
> I'm assuming the former is equivalent to
>
>     for key in a_dict.iterkeys() :

Never assume. A better approach would be to experiment:


>>> a_dict = {'name':'apple', 'color':'red', 'texture':'smooth',
'shape':'sphere'}
>>> for i in a_dict: print i
color
shape
name
texture
>>> for i in a_dict.iterkeys(): print i
color
shape
name
texture
>>> for i in a_dict.itervalues(): print i
red
sphere
apple
smooth
>>> for i in a_dict.iteritems(): print i
('color', 'red')
('shape', 'sphere')
('name', 'apple')
('texture', 'smooth')




More information about the Python-list mailing list