sábado, 31 de agosto de 2013

Progress Report Update

This weeks I have been working on how to providing initial data for our models. I thought that use a dictionary type could be an easy way. But it isn't... I want to preserve the order of inserted data, nor store the data sorted by the key (as dictionary type do)!
But, after hours of pain, something came to my rescue : a dictionary that remembers insertion order! From python 2.7, OrderedDict is supported [1].
This example will show you a quick idea of how it works:

Case 1: numbers for dict keys 

>>> from collections import OrderedDict
>>> from pprint import pprint
>>> 
>>> V = {
...     '1': ['time',  'cost'],
...     '2': ['time',  'cost'],
...     '3': ['time'],
...      }
>>>      
... pprint (V)
{'1': ['time', 'cost'], '2': ['time', 'cost'], '3': ['time']}
>>> 
>>> V = OrderedDict((
...         ('1', ['time',  'cost']),
...         ('2', ['time',  'cost']),
...         ('3', ['time'])
...         ))
>>> pprint (V)
OrderedDict([('1', ['time', 'cost']), ('2', ['time', 'cost']), ('3', ['time'])])
Case 2: strings for dict keys 

>>> from collections import OrderedDict
>>> from pprint import pprint
>>> 
>>> V = {
...     'train': ['time',  'cost'],
...     'bus':   ['time',  'cost'],
...     'car':   ['time'],
...      }
>>> pprint (V)
{'bus': ['time', 'cost'], 'car': ['time'], 'train': ['time', 'cost']}
>>> 
>>> V = OrderedDict((
...         ('train', ['time',  'cost']),
...         ('bus',   ['time',  'cost']),
...         ('car',   ['time'])
...         ))
>>> pprint (V)
OrderedDict([('train', ['time', 'cost']), ('bus', ['time', 'cost']), ('car', ['time'])])
While in case 1 (dictionary keys with numbers) the outcome is similar, with strings for dictionary keys (case 2), it isn't: only the order is preserved for ordered dictionary.

[1] https://pypi.python.org/pypi/ordereddict

No hay comentarios:

Publicar un comentario