简体   繁体   中英

Python support sorted dictionary — similar to C++ map?

I am using Python 2.7.x. I have a dictionary (I mean {} ), key is int and value is string. I want to retrieve the key which has the minimal integer value. In C++, I think we can use map, which sort keys. And in Python, not sure if anything similar we can leverage? If my understanding is correct, Python dictionary (I mean {} ) is not sorted by key.

thanks in advance, Lin

Update

The OP has expressed a need for O(1) performance when finding the minimum key in a dictionary. Try the sortedcontainers module. It offers a SortedDict class:

>>> from sortedcontainers import SortedDict
>>> d = SortedDict({100: 'a', 27: 'b', 1234: 'c'})
>>> d.keys()
SortedSet([27, 100, 1234], key=None, load=1000)
>>> d.keys()[0]
27
>>> d[d.keys()[0]]
'b'

For a Python builtin dictionary you can use min(d) to find the lowest key:

>>> d = {100: 'a', 27: 'b', 1234: 'c'}
>>> print(d)
{1234: 'c', 27: 'b', 100: 'a'}
>>> print(min(d))
27
>>> print(d[min(d)])
b

In Python, dictionaries are represented internally by hash tables so you cannot natively get back the keys in sorted order. You can use sorted(d.keys()) to return a list of keys in sorted order. You can also use collections.OrderedDict if you pre-sort the keys. If you do not know the order of the keys ahead of time and you need to maintain the keys in sorted order as you insert values, you could take a look at this library for the SortedDict type.

Building off of @mhawke 's answer, you can simply do:

d = {1 : "a", 2 : "b", 3 : "c" }
print d[min(d.keys())] # => 'a'

There are binary tree implementations in Python:

https://pypi.python.org/pypi/bintrees/2.0.2

You can also use the blist.sorteddict .

You could also use the built-in bisect module to maintain a sorted list of tuples.

If all you care about is finding the minimum and you don't actually care about maintaining a sort, you can use the built-in heapq module to maintain a min-heap data structure which gives you constant time access to the minimal element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM