-1

I initialised a dictionary with the following key-value pairs:

count = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r": 0, "s":0, "t": 0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0}

However, when I printed the same, the pairs had been interchanged except for the first and last one:

{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}

This gave me the wrong answer to the problem I was trying to solve. Why is this happening?

Mihir94
  • 3
  • 2
  • Because python dictionaries are unsorted. – trotta Jun 13 '17 at 15:32
  • 1
    Except Python 3.6 where they start being ordered – vZ10 Jun 13 '17 at 15:33
  • @trotta It's not *quite* that simple any more. CPython 3.6, as an implementation detail, now *does* store keys in the order they were originally inserted (like an `OrderedDict`). – chepner Jun 13 '17 at 15:34
  • More than unsorted: they have no (guaranteed) order. I believe the python 3.6 order is an implementation detail and not to be relied upon. @Mihir94 can you share some details of the problem you are trying to solve? It may be that a `dict` isn't the best data structure to use – Patrick Haugh Jun 13 '17 at 15:35
  • https://pastebin.com/raw/w9UvMPEA – cs95 Jun 13 '17 at 15:36
  • @PatrickHaugh the problem requires you to count the occurrence of each character in a given string and then report the top 3 commonly occurring characters. I did manage to solve it by initialising 2 arrays. I just wanted to know the reason for the dictionary ambiguity. – Mihir94 Jun 14 '17 at 10:22
  • @Mihir94 Python can do that for you with the [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) – Patrick Haugh Jun 14 '17 at 14:29

1 Answers1

0

If you want to preserve the order you should use collections.OrderedDitct instead of a standard dictionary.

vZ10
  • 2,468
  • 2
  • 23
  • 33