0

I have been trying to print the dictionary output within the required format, but somehow python prints in its order.

identifiers = {
    "id" : "8888",
    "identifier" :"7777",
    }

for i in range(1, 2):
    identifiers['id'] = "{}".format(i)
    print str(identifiers).replace("'","\"")

My code ouput:

{"identifier": "7777", "id": "1"}

Output Required:

{"id": "1" , "identifier": "7777"}

Thanks!

Captain-Robot
  • 71
  • 2
  • 8
  • 1
    Dictionaries are unordered, so the order that the keys are added doesn't necessarily reflect what order you gave them. If you care about order check this: [link](https://stackoverflow.com/questions/20110627/print-original-input-order-of-dictionary-in-python) – Jacopo Repossi Feb 03 '19 at 19:43

1 Answers1

2

By nature, python dictionaries have no set order - even if you have defined you dictionary in a specific order, this order is not stored (or remembered) anywhere. If you want to maintain dictionary order, you can use an OrderedDict:

from collections import OrderedDict
identifiers = OrderedDict([
    ("id", "8888"), #1st element is the key and 2nd element is the value associated with that key
    ("identifier", "7777")
    ])

for i in range(1, 2):
    identifiers['id'] = "{}".format(i)

for key, value in identifiers.items(): #simpler method to output dictionary values
    print key, value

This way, the dictionary you have created operates exactly like a normal python dictionary, except the order in which key-value pairs were inserted (or to be inserted) is remembered. Updating values in the dictionary will not affect the order of the key-value pairs.

  • 2
    Starting python 3.6 dictionaries are insertion ordered as well: https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6. – Primusa Feb 03 '19 at 19:46