[Tutor] Lists with just an item
Brian van den Broek
broek at cc.umanitoba.ca
Mon Nov 21 10:35:48 CET 2005
Negroup - said unto the world upon 2005-11-21 03:26:
> Hi all.
> In my application I have chosen as data structure a list of
> dictionaries. Each dictionary has just one key and the corresponding
> value.
>
> structure = [{'field1': lenght1}, {'field2': lenght2}, ........]
>
> Initially, to obtain the key and the value I used this code,
>
> for structure in record_structure:
> field_name = structure.keys()[0]
> displacement = structure[field_name]
>
> but after some thoughts I arrived to:
> field_name, displacement = structure.items()[0]
>
> which to me seems a lot better.
>
> 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
> something better?
>
> Thanks!
Hi Negroup,
why not just make structure a dict:
structure = {'field1': lenght1, 'field2': lenght2}
What does having a list of dicts all with a single key add but a layer
of referencing when you want to access?
If you are trying to preserve order and your key examples are real:
>>> structure = {'field1': 1, 'field2': 2, 'field3': 3}
>>> for item in sorted(structure.items()): print item
('field1', 1)
('field2', 2)
('field3', 3)
>>>
Best,
Brian vdB
More information about the Tutor
mailing list