0

I am using the following code to print keys and values of a dict.

for key, val in index1.items():
            print("++++++++")
            print ( key)
            print (val)
            print("++++++++")

I want it's to be printed in the same order as it was inserted. Currently, it's not following that.

John
  • 35
  • 4
  • What version of Python? `dict`s are insertion-ordered starting with Python 3.6. Otherwise you'll need to use [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict). – 0x5453 Mar 30 '22 at 19:07

1 Answers1

-2

It is not printing in the same order because the order is not important since you can't get any values with indexes because you use strings as keys to get values. But you can always use .sorted() if you want (it doesn't impact anything in the dictionary, just the printing part)

BokiX
  • 412
  • 2
  • 14
  • This answer is wrong in several ways. Since Python 3.6 dicts are ordered based on insertion order. Second you can have any hashable type as the key, not just strings. – Cory Kramer Mar 30 '22 at 19:10
  • Okay, but that's not the point, strings are most common and that's why I said that because this is a question that a beginner would ask and I didn't want to confuse anyone. And I don't see why my answer is wrong since the order doesn't matter? – BokiX Mar 30 '22 at 19:19
  • The OP literally said "I want it's to be printed in the same order as it was inserted" so it is important by being a requirement. And strings being the most common key type for a dictionary is both an unsupported anecdotal claim and irrelevant. Regardless this is addressed in detail in the post I linked above. – Cory Kramer Mar 30 '22 at 19:21