Python
Data Structures
Key-Value Pair
Ordered Dictionary
Programming Tips

How to keep keys/values in same order as declared?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, keeping keys and values in the order they were declared is mostly a matter of choosing the right mapping type for your runtime. In modern Python, ordinary dict already preserves insertion order, so the real question is not “how do I force order,” but “do I need only insertion order, or do I need explicit ordered-dictionary behavior.”

Use Plain dict in Modern Python

In Python 3.7 and later, insertion order is part of the language guarantee for dictionaries.

python
1settings = {
2    "host": "db.example.com",
3    "port": 5432,
4    "ssl": True,
5}
6
7for key, value in settings.items():
8    print(key, value)

The keys come out in the order they were inserted. That means for many normal use cases, a plain dictionary is already enough.

This is what most people mean by “same order as declared.” They do not mean sorted order. They mean insertion order.

Insertion Order Is Not Sorting

These are different requirements. Consider this example:

python
1data = {}
2data["b"] = 2
3data["a"] = 1
4data["c"] = 3
5
6print(list(data.keys()))

Output:

python
['b', 'a', 'c']

The keys stay in insertion order, not alphabetical order. If you want alphabetical output, you have to sort explicitly.

python
for key in sorted(data):
    print(key, data[key])

That is a different problem from preserving declaration order.

When OrderedDict Still Matters

collections.OrderedDict is still useful when you need ordering operations, not just passive order preservation.

python
1from collections import OrderedDict
2
3od = OrderedDict()
4od["host"] = "db.example.com"
5od["port"] = 5432
6od["ssl"] = True
7
8od.move_to_end("host")
9print(list(od.keys()))

Use OrderedDict when you need features such as:

  • 'move_to_end'
  • explicit ordering APIs
  • compatibility with older Python versions
  • code that wants to signal ordered semantics very clearly

If you only want stable insertion order, plain dict is usually simpler.

Updates Do Not Reinsert Keys

Another detail people miss is that changing the value for an existing key does not move that key to the end in a normal dictionary.

python
data = {"a": 1, "b": 2, "c": 3}
data["b"] = 99
print(list(data.keys()))

The output stays:

python
['a', 'b', 'c']

That is usually what you want. If you need “last updated key goes to the end,” then OrderedDict is a better match.

Order in JSON and Other Output

A common reason order matters is stable serialized output.

python
1import json
2
3payload = {
4    "name": "service-a",
5    "region": "us-east-1",
6    "enabled": True,
7}
8
9print(json.dumps(payload))

Because the dictionary preserves insertion order, the JSON output usually reflects the same sequence. But if you do this:

python
print(json.dumps(payload, sort_keys=True))

then you are explicitly asking for alphabetical sorting, which overrides insertion order. That difference is worth remembering when configuration or snapshot tests depend on stable output.

Common Pitfalls

  • Confusing insertion order with sorted order.
  • Reaching for OrderedDict by habit when a normal dict already solves the problem.
  • Expecting a key to move when its value is updated.
  • Forgetting that older Python versions did not guarantee dict ordering in the same way.
  • Sorting keys during output and then wondering why declaration order disappeared.

Summary

  • In modern Python, dict preserves insertion order by default.
  • Use a plain dictionary when you only need keys and values to stay in declaration order.
  • Use OrderedDict when you need explicit ordering operations or old-version compatibility.
  • Updating a value does not change the key’s position in a normal dictionary.
  • Be clear about whether you want insertion order or sorted order, because they are different behaviors.

Course illustration
Course illustration

All Rights Reserved.