0

Using Python 3.4, I am trying to sort a dictionary with two identical entries. When I run,

my_dict = {
    '6/18/2015': [6, 'a'],
    '6/19/2015': [18, 't'],
    '6/17/2015': [3, 'r']
    }
for key, value in sorted(my_dict.iteritems(), key=lambda kvt: kvt[1][0]):
        print key, ':', value

I get a nicely printed result.

But when I use my actual data, which look more like:

my_dict = {
    '6/18/2015': [6, 'a'],
    '6/19/2015': [18, 't'],
    '6/18/2015': [3, 'r'] #note the duplicate date
    }
for key, value in sorted(my_dict.iteritems(), key=lambda kvt: kvt[1][0]):
        print key, ':', value

the result just drops any repeated rows.

What am I doing wrong?

(Edited to add: thanks all for helping. Correct answer understood. In case anyone else has this problem, my dictionary's keys were actually tuples. Multiple tuples began with the same value and this confused me)

Joe
  • 5
  • 3
  • 1
    The keys of a dictionary must be unique. You might therefore want to store lists of values to capture multiple datapoints from the same day – inspectorG4dget Jul 08 '15 at 17:03
  • 1
    Dictionaries cannot contain duplicate keys. [Use a different data structure.](https://docs.python.org/3/library/stdtypes.html) – TigerhawkT3 Jul 08 '15 at 17:03

1 Answers1

0

A dictionary cannot have duplicate keys, but you can create a list to store multiple values for the same key:

my_dict = {
  '6/18/2015': [[6, 'a'], [3,'r']],
  '6/19/2015': [18, 't'],
}
FriC
  • 786
  • 10
  • 14