Fundamentals 4 min read

6 Surprising Python Dictionary Tricks You Probably Didn’t Know

Discover six unexpected Python dictionary features—from insertion-order preservation in Python 3.7+, safe key access with .get(), immutable key requirements, the power of collections.defaultdict, the concise merge operator | in Python 3.9+, to using popitem() for stack-like behavior—each illustrated with clear code examples.

Code Mala Tang
Code Mala Tang
Code Mala Tang
6 Surprising Python Dictionary Tricks You Probably Didn’t Know

Python dictionaries are widely used, yet they still hold many surprising and sometimes confusing behaviors.

1. Dictionary keys remember insertion order (Python 3.7+)

You might think dictionaries are unordered, but since Python 3.7 they preserve the order in which keys are inserted.

<code>my_dict = {
'first': 1,
'second': 2,
'third': 3
}
print(my_dict)</code>

This makes a dictionary feel more like a list in some cases, such as a queue where order matters.

2. Difference between .get() and []

If you try to access a missing key with [] , you get a KeyError . Using .get() returns None (or a default you provide), preventing crashes when handling uncontrolled data.

<code>print(my_dict.get('missing_key'))</code>

3. Dictionary keys must be immutable

Keys must be of immutable types such as strings, numbers, or tuples. Attempting to use a list as a key raises an error because mutable objects cannot be reliably hashed.

<code>my_dict = { (1, 2): "a tuple as key" }</code>

4. The usefulness of defaultdict

The collections.defaultdict automatically provides a default value for missing keys, eliminating the need for manual existence checks.

<code>from collections import defaultdict

count_dict = defaultdict(int)
count_dict['apples'] += 1
print(count_dict)</code>

5. Merging dictionaries with | (Python 3.9+)

Python 3.9 introduced the | operator to merge dictionaries more succinctly than .update() or unpacking.

<code>dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)</code>

Note: This syntax works only in Python 3.9 and later.

6. popitem() – stack‑like functionality

The popitem() method removes and returns the last key‑value pair, making it useful for implementing a stack with a dictionary.

<code>stack_dict = {'first': 1, 'second': 2, 'third': 3}
print(stack_dict.popitem())
print(stack_dict)</code>

Remember to use popitem() when you need flexible, stack‑style behavior.

pythonprogrammingData Structurescode examplesdictionarytips
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.