Calvin Cheng
Calvin Cheng

Reputation: 36506

A better way to reorganize dictionary key, value pairs?

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".)

Upvotes: 1

Views: 332

Answers (3)

Blckknght
Blckknght

Reputation: 104712

How about:

dates, observations = zip(*date_dict.items())

Then pack up the dates and observations lists however you like.

You can sort with the same construct:

dates, observations = zip(*sorted(date_dict.items()))

Upvotes: 1

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Maybe:

new_dict = {'datetime': date_dict.keys(), 'observations': date_dict.values()}

In case you need order try to use OrderedDict instead of dict:

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

Upvotes: 5

Burhan Khalid
Burhan Khalid

Reputation: 174624

Are you sure you need a dictionary? I think a list of tuples does what you want better:

observations = [('2003-08-13',1),...]

Upvotes: 0

Related Questions