1

How would I get the some value, alphabetically, from a dictionary in python?

For example, if we have:

dict = {'A':1, 'B':7, 'C':3}

How would I get it to return the highest value in the alphabet from the dictionary (1), the second highest (7) and the lowest (3)?

mdml
  • 22,442
  • 8
  • 58
  • 66
David
  • 1,398
  • 1
  • 14
  • 20
  • 1
    If those are what you want, a dictionary may not be the best structure to store your data in. Consider instead an iterable structure such as a list of tuples ```[("A", 1), ...]``` – wnnmaw Jun 12 '14 at 18:28
  • Duplicate of http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value – Dan Getz Jun 12 '14 at 18:30

3 Answers3

3

The pure-Python sortedcontainers module has a SortedDict type that can help you. It maintains the dict keys automatically in sorted order and is well documented and tested. You use it just as you would a dict:

>>> from sortedcontainers import SortedDict
>>> d = SortedDict({'A': 1, 'B': 7, 'C': 3})
>>> list(d.keys())
['A', 'B', 'C']

Iterating keys will be much faster this way if you do a lot of edits than constantly re-sorting the keys manually. The sorted containers module is very fast and has a performance comparison page with benchmarks against alternative implementations.

GrantJ
  • 8,162
  • 3
  • 52
  • 46
0

You can sort the keys, then get the value based on the index

>>> def get_alphabetically(my_dict, indx):
       key = list(sorted(my_dict))[indx]
       return my_dict[key]
>>> get_alphabetically({'A':1, 'B':7, 'C':3}, 0) # "Highest" value in alphabet
1
>>> get_alphabetically({'A':1, 'B':7, 'C':3}, -1) # "Lowest" value in alphabet
3
>>> get_alphabetically({'A':1, 'B':7, 'C':3}, 1) # "Second highest" value in alphabet
7

Having said this, you may have an XY problem, where you are not using the appropriate data structure for your problem.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
  • But, of course this gives an O(nlogn) solution. Ideally, you should be able to do something like this in O(logn) operations I would think. – mgilson Jun 12 '14 at 18:31
  • @mgilson I guess, but do we know the size of the dictionary? If it's not large, is that an issue? Anyway, I think the correct answer would not be to use this function, but to rethink the data structure in the first place. – SethMMorton Jun 12 '14 at 18:33
  • Yes, a new datastructure is what I'm proposing. I'm not saying that this answer is _wrong_. Given OP's constraint that you're using a `dict`, this is about as good as you _can_ do. – mgilson Jun 12 '14 at 19:02
0
sorted(my_dict.items(),reverse=True,key=lambda x:x[1])

I think would essentially do what you want ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179