0

I've been searching for the answer to this for a while, but no joy.

I have a dict containing hotel names and prices.

mydict = {'HotelA': 100, 'HotelB': 300, 'HotelC': 200}

I would simply like to iterate over the dict and return a separate dict whose values rank the keys based on lowest to highest values, eg:

mynewdict = {'HotelA': 1, 'HotelB': 3, 'HotelC': 2}

I am aware of how to use sorted to iterate over a dictionary and provide an ordered list, but am unsure as to the best way to handle the above. All help greatly appreciated.

user2781522
  • 119
  • 10
  • show us code. what have you already tried? –  Sep 15 '13 at 16:11
  • I'm pretty new to Python and haven't found anything I CAN try yet, hence coming here and explaining exactly what I want to do in explicit terms. – user2781522 Sep 15 '13 at 16:12
  • have a look at http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value and the builtin `enumerate` function –  Sep 15 '13 at 17:16

1 Answers1

0
>>>import operator
>>>mydict = {'HotelA': 100, 'HotelB': 300, 'HotelC': 200}
#Sorting a list of tuples based on their second element (the value ex.: 100, 200, 300)
>>>sorted_list = sorted(mydict.iteritems(), key=operator.itemgetter(1))

In that case sorted_list will be an ordered list of tuples, each tuples containing the name of the hotel and the value:

[('HotelA', 100), ('HotelC', 200), ('HotelB', 300)]
Ketouem
  • 3,820
  • 1
  • 19
  • 29