[Tutor] Lists with just an item

Alan Gauld alan.gauld at freenet.co.uk
Mon Nov 21 11:09:13 CET 2005

> Each dictionary has just one key and the corresponding
> value.
> structure = [{'field1': lenght1}, {'field2': lenght2}, ........]

I'd use a tuple rather than a dictionary here:

structure = [('field1', lenght1), ('field2', lenght2), ........]

> but after some thoughts I arrived to:
> field_name, displacement = structure.items()[0]
>At this point I don't like much that [0] to access a list that I know
> always contains a single element. Can I improve the code with

you can now do

for field_name, displacement in structure:
     # work with values here

Is that any better?

Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list