0

I have a dictionary which has frequency (int) as keys and numbers (list) as values. If I iterate through the list as given below will it give the frequencies in ascending order.

for freq in dic:
   print(freq)

Will the frequency be in ascending order?

Omkar Vedak
  • 25
  • 1
  • 5
  • 1
    Does this answer your question? [How do you retrieve items from a dictionary in the order that they're inserted?](https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted) – Mitch Wheat May 13 '21 at 00:25
  • 1
    This depends on your version of Python. If you're using Python 3.7+ `dicts` are ordered by insertion. If earlier, you need to use `collections.OrderedDict` – PacketLoss May 13 '21 at 00:25
  • Generally, we shouldn't keep in mind that thought for default data structures because it might be changed in the future and nothing guarantees. – Tuan Chau May 13 '21 at 00:50
  • 1
    @TuanChau the fact that iteration order is the same as insertion order for `dict` is now a guaranteed property of CPython and will not be changing. It only becomes an issue if you're using an older version of Python. – Mark Ransom May 13 '21 at 02:19

1 Answers1

0

If you know that the items were inserted into the dict in sorted order, recent versions of Python will maintain that order. If you really need to be sure, it's easy to sort them:

for freq in sorted(dic.items()):
   print(freq)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622