David
David

Reputation: 1438

Return a value from a dictionary alphabetically

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)?

Upvotes: 1

Views: 108

Answers (3)

GrantJ
GrantJ

Reputation: 8709

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.

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 114028

sorted(my_dict.items(),reverse=True,key=lambda x:x[1])

I think would essentially do what you want ...

Upvotes: 0

SethMMorton
SethMMorton

Reputation: 48775

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.

Upvotes: 0

Related Questions