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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With