Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 796
Lin Ma Avatar asked Feb 11 '16 01:02

Lin Ma


People also ask

Does Python have a sorted dictionary?

Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function.

Is map the same as dictionary in Python?

To answer the question in the title, it is the same. A map seen as a datastructure is the same concept as a dict . dict s also use hashes to map keys to values. That's why java developers call it hashmap.

Is map in C++ same as dictionary in Python?

They're the same thing, but a map has fixed object types. dict() maps a hashable type (like strings,or doubles) to an object of any type.

Are Python dictionary keys sorted?

Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.


2 Answers

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
like image 133
mhawke Avatar answered Sep 20 '22 19:09

mhawke


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.

like image 31
Kurt Stutsman Avatar answered Sep 19 '22 19:09

Kurt Stutsman