I begin with a simple python dictionary like this:-
In [29]: date_dict
Out[29]:
{'2003-06-24': 2,
'2003-08-13': 1,
'2003-08-19': 2,
'2003-08-22': 1,
'2003-08-24': 5}
with the key being a date and the value an integer.
My goal is to reorganize the data in this dictionary into:-
{'datetime': ['2003-08-13',
'2003-08-19',
'2003-06-24',
'2003-08-24',
'2003-08-22'],
'observations': [1, 2, 2, 5, 1]}
which maintains the data relationship between the list held by the datetime key and the list held by the observations key.
This is my solution to get this done:-
In [35]: new_dict
Out[35]: {'datetime': [], 'observations': []}
In [36]: for key, value in date_dict.iteritems():
....: new_dict['datetime'].append(key)
....: new_dict['observations'].append(value)
In [37]: new_dict
Out[37]:
{'datetime': ['2003-08-13',
'2003-08-19',
'2003-06-24',
'2003-08-24',
'2003-08-22'],
'observations': [1, 2, 2, 5, 1]}
My question is – are there alternative (better still, if more efficient) methods of doing this?
(Note that it is critical to maintain the data-relationship across the two lists, i.e. in the original date_dict, “2003-08-24” corresponds to value “5”. After the data is reorganized, the 3rd index of the ‘datetime’ list is “2003-08-24” which correctly corresponds to the 3rd index of the ‘observations list’ as “5”.)
Maybe:
In case you need order try to use OrderedDict instead of dict: