Python Dictionaries · Lesson 56 of 149

Python Dictionary Ordering, Merging and Copying

What you will learn

  • That a dictionary keeps insertion order, and how changes affect it
  • That equality ignores order, and how OrderedDict differs
  • How to get the first and last keys, and to go backwards
  • Ways to merge: |, **, update, ChainMap, summing values and a deep merge
  • Alias, shallow copy and deep copy of dictionaries
  • A read-only view with MappingProxyType

1. Insertion order

A dictionary remembers the order in which its keys were first added. Looping, list(d) and printing all follow that order. The Python documentation states that this is guaranteed since Python 3.7, so you can rely on it:

d = {}
d["b"] = 1
d["a"] = 2
d["c"] = 3
print(d)
print(list(d))
{'b': 1, 'a': 2, 'c': 3}
['b', 'a', 'c']

The order is the order of insertion, not alphabetical and not by value. (Very old versions, before 3.7, made no such promise, so code for them could not rely on it.)

Quick check: in what order does `{"z": 1, "a": 2}` list its keys?

["z", "a"], the order in which they were written.

2. How changes affect the order

Action Effect on the order
change the value of an existing key the key keeps its place
add a new key it goes at the end
delete a key, then add it again it goes at the end
d = {"b": 1, "a": 2, "c": 3}
d["b"] = 100
print(d)

del d["a"]
d["a"] = 2
print(d)
{'b': 100, 'a': 2, 'c': 3}
{'b': 100, 'c': 3, 'a': 2}

Updating b left it first. Deleting a and adding it back moved it to the end. This gives a way to move a key to the end:

d["c"] = d.pop("c")
print(d)
{'b': 100, 'a': 2, 'c': 3}

pop removes the pair and returns the value, and the assignment puts it back at the end.

3. First and last, and backwards

d = {"b": 100, "a": 2, "c": 3}
print(next(iter(d)))
print(list(d)[-1])
print(next(reversed(d)))
b
c
c
  • next(iter(d)) is the first key.
  • list(d)[-1] or next(reversed(d)) is the last key. reversed(d) needs Python 3.8 or later, and the list version copies every key, so reversed is better for big dictionaries.
  • popitem() removes the last pair added (lesson 9.2).

To go backwards through the pairs:

x = {"a": 1, "b": 2}
print(list(reversed(x)))
print(dict(reversed(list(x.items()))))
['b', 'a']
{'b': 2, 'a': 1}

4. Equality ignores order

Two dictionaries are equal when they have the same pairs, in any order. But the order of the keys can still differ:

e1 = {"a": 1, "b": 2}
e2 = {"b": 2, "a": 1}
print(e1 == e2)
print(list(e1) == list(e2))
True
False

If order must count, compare list(e1.items()) == list(e2.items()), or use collections.OrderedDict. It is an older dictionary type that was made for order and still differs from a regular dictionary in a few ways (according to the Python documentation):

from collections import OrderedDict

print(OrderedDict(a=1, b=2) == OrderedDict(b=2, a=1))
print(OrderedDict(a=1, b=2) == {"b": 2, "a": 1})
False
True
  • Two OrderedDicts are equal only if the order matches too.
  • OrderedDict has move_to_end(key) and popitem(last=False) to work from either end.
od = OrderedDict(a=1, b=2, c=3)
od.move_to_end("a")
print(od)
print(od.popitem(last=False))
OrderedDict({'b': 2, 'c': 3, 'a': 1})
('b', 2)

You rarely need it today. A regular dictionary is enough unless you rely on these extra methods or on order-sensitive equality.

Sorted dictionaries

A dictionary is not kept sorted, but you can build a new one in sorted order from sorted pairs:

print(dict(sorted({"b": 2, "a": 1, "c": 3}.items())))
print(dict(sorted({"b": 2, "a": 1}.items(), key=lambda kv: kv[1], reverse=True)))
{'a': 1, 'b': 2, 'c': 3}
{'b': 2, 'a': 1}

5. Merging dictionaries

There are several ways. For a repeated key, the later dictionary wins in each one:

defaults = {"theme": "light", "size": 12}
user = {"size": 16}

print(defaults | user)
print({**defaults, **user})

merged = defaults.copy()
merged.update(user)
print(merged)
{'theme': 'light', 'size': 16}
{'theme': 'light', 'size': 16}
{'theme': 'light', 'size': 16}
Way Notes
a | b new dictionary (Python 3.9 and later)
{**a, **b} new dictionary, any Python 3 version (lesson 8.3)
a.update(b) or a |= b changes a in place

Put the defaults first and the user's choices last, so the user wins. Swapping the order flips the result: {**user, **defaults} would reset the size to 12.

ChainMap: layers without copying

collections.ChainMap joins dictionaries into one view without copying them. A lookup tries the first dictionary, then the next. This suits layered settings:

from collections import ChainMap

cm = ChainMap(user, defaults)
print(cm["size"], cm["theme"])
defaults["theme"] = "dark"
print(cm["theme"])
cm["new"] = 1
print(user)
16 light
dark
{'size': 16, 'new': 1}

The ChainMap sees later changes in defaults (a copy would not). Writing goes to the first dictionary only.

Adding up values

When keys repeat and you want to combine the values, loop, or use Counter:

a = {"x": 1, "y": 2}
b = {"y": 10, "z": 5}

total = dict(a)
for k, v in b.items():
    total[k] = total.get(k, 0) + v
print(total)

from collections import Counter
print(dict(Counter(a) + Counter(b)))
{'x': 1, 'y': 12, 'z': 5}
{'x': 1, 'y': 12, 'z': 5}

Counter adds counts. Counter arithmetic drops results whose count is zero or less (lesson 9.6).

Deep merge

| replaces a whole inner dictionary. To merge inside nested dictionaries, write a function that calls itself (recursion, lesson 11.6):

import copy

def deep_merge(base, extra):
    out = copy.deepcopy(base)
    for k, v in extra.items():
        if isinstance(v, dict) and isinstance(out.get(k), dict):
            out[k] = deep_merge(out[k], v)
        else:
            out[k] = copy.deepcopy(v)
    return out

base = {"db": {"host": "h", "port": 1}, "debug": False}
extra = {"db": {"port": 2}, "debug": True}
print(deep_merge(base, extra))
print({**base, **extra})
{'db': {'host': 'h', 'port': 2}, 'debug': True}
{'db': {'port': 2}, 'debug': True}

The plain merge lost "host", because it replaced the whole db dictionary. The deep merge kept it.

6. Alias, shallow copy, deep copy

You know this from lessons 2.7 and 7.5, and it applies to dictionaries exactly:

Code What you get
alias = d the same dictionary (two names)
d.copy(), dict(d), {k: v for k, v in d.items()} a shallow copy: new dictionary, shared values
copy.deepcopy(d) a deep copy: nothing shared
orig = {"k": [1], "n": {"m": 1}}
shallow = orig.copy()
deep = copy.deepcopy(orig)

shallow["k"].append(2)
shallow["new"] = 1
deep["n"]["m"] = 99

print(orig)
print(shallow["k"] is orig["k"])
print(deep)
{'k': [1, 2], 'n': {'m': 1}}
True
{'k': [1], 'n': {'m': 99}}
  • Adding the key "new" to the shallow copy did not touch orig (the outer dictionaries are separate).
  • Appending to shallow["k"] did change orig, because both hold the same list.
  • Changing deep changed nothing else.

7. A read-only view

types.MappingProxyType gives a read-only window onto a dictionary. The owner can still change the dictionary, but through the view nobody can:

from types import MappingProxyType

ro = MappingProxyType({"a": 1})
print(ro["a"])
ro["b"] = 2
1
TypeError: 'mappingproxy' object does not support item assignment

It is useful for exposing settings without letting other code change them.

Worked example: layered settings

A program has built-in defaults, a settings file and command-line choices. The later layer overrides the earlier one.

defaults = {"theme": "light", "size": 12, "lang": "en"}
file_settings = {"size": 14, "lang": "bn"}
command_line = {"theme": "dark"}

settings = {**defaults, **file_settings, **command_line}
print(settings)
print(list(settings))

changed = {k for k in settings if settings[k] != defaults[k]}
print(sorted(changed))
{'theme': 'dark', 'size': 14, 'lang': 'bn'}
['theme', 'size', 'lang']
['lang', 'size', 'theme']
Layer Keys it adds or replaces
defaults all three
file_settings size, lang
command_line theme

The keys keep the order of the first layer, because replacing a value does not move a key. The settings are made up.

Common mistakes

  • Assuming a dictionary is sorted. It keeps insertion order, not sorted order.
  • Expecting == to compare order. It does not.
  • Merging in the wrong order, so the defaults override the user's choices.
  • Using | to merge nested settings, which replaces whole inner dictionaries. Use a deep merge.
  • Using .copy() and changing nested values. It is shallow.
  • Using | or |= on Python before 3.9.

Key takeaways

  • A dictionary keeps insertion order (guaranteed since Python 3.7); changing a value keeps the place, while delete-and-add moves a key to the end.
  • Equality ignores order; OrderedDict compares order and has move_to_end.
  • Merge with a | b, {**a, **b} or update; the later dictionary wins; use ChainMap for layers and a recursive function for a deep merge.
  • copy(), dict(d) and comprehensions give shallow copies; copy.deepcopy gives an independent copy.
  • MappingProxyType offers a read-only view.

Practice

1. In what order are the keys after d = {"a": 1, "b": 2} then d["a"] = 9?

Show answer

["a", "b"]. Changing the value of an existing key keeps its place.

2. What is the order after del d["a"] and d["a"] = 1 on {"a": 0, "b": 2}?

Show answer

["b", "a"]. The re-added key goes to the end.

3. Is {"a": 1, "b": 2} == {"b": 2, "a": 1} true?

Show answer

Yes. Dictionary equality ignores the order of the keys.

4. Merge defaults and user so that user wins, in two ways.

Show answer

defaults | user and {**defaults, **user}.

5. Why is {**a, **b} a poor choice for merging nested settings?

Show answer

It replaces an entire inner dictionary when the key is repeated, so other inner keys are lost. Use a recursive deep merge.

6. After b = a.copy() for a = {"k": [1]}, does b["k"].append(2) change a?

Show answer

Yes. The copy is shallow, so both dictionaries share the same list. Use copy.deepcopy(a) for independence.