Sitemap
Ali Shahed

Ali Shahed

ML | AI

Dictionary Initialization methods in Python 🐍

2 min readJul 25, 2025

--

Press enter or click to view image in full size

Dictionaries are one of Python’s most powerful built-in data types, used to store key-value pairs. Whether you’re writing a quick script or building a complex system, initializing dictionaries efficiently can make your code more readable and expressive.

Get Ali Shahed’s stories in your inbox

Join Medium for free to get updates from this writer.

This guide concisely explores various ways to initialize dictionaries in Python, complete with pros, cons, and illustrative examples.

1. Curly Braces {} – The Classic

d = {'a': 1, 'b': 2}

Pros:

  • Simple and readable

Cons:

  • Static; not suitable for dynamic generation

2. Using the dict() Constructor

d = dict(a=1, b=2)

Pros:

  • Clean syntax for string keys

Cons:

  • Keys must be valid Python identifiers (e.g., dict(foo-bar=1) is invalid)

3. From an Iterable of Tuples

d = dict([('a', 1), ('b', 2)])

Pros:

  • Works dynamically with any iterable

Cons:

  • Verbose for small, static dictionaries

4. Dictionary Comprehension

d = {k: k**2 for k in range(5)}

Pros:

  • Best for programmatic dictionary creation

Cons:

  • May be less readable with complex logic

5. Zipping Keys and Values

keys = ['x', 'y']
values = [10, 20]
d = dict(zip(keys, values))

Pros:

  • Elegant method for pairing two sequences

Cons:

  • Silently truncates if sequences differ in length

6. Using fromkeys()

d = dict.fromkeys(['a', 'b'], 0)

Pros:

  • Quickly assigns the same initial value to multiple keys

Cons:

  • Mutable default values are shared (potential pitfall!)
d = dict.fromkeys(['a', 'b'], [])
d['a'].append(1)
print(d) # Output: {'a': [1], 'b': [1]} (unexpected!)

7. Using defaultdict from collections

from collections import defaultdict

d = defaultdict(int)
d['missing'] += 1

Pros:

  • Automatically initializes missing keys

Cons:

  • Slightly different behavior from standard dictionaries

8. Merging with ** Unpacking

a = {'x': 1}
b = {'y': 2}
d = {**a, **b}

Pros:

  • Clean syntax for merging dictionaries

Cons:

  • Requires Python 3.5 or later

9. Creating an Empty Dictionary

d = {}
# or
d = dict()

Pros:

  • Fast and idiomatic

Cons:

  • Empty until filled

🧠 Quick Reference Table

Press enter or click to view image in full size

đŸ‘©â€đŸ« Conclusion

Selecting the right initialization method enhances code readability, minimizes bugs, and ensures your dictionary behaves as intended. Being aware of potential pitfalls like shared mutable defaults or silent truncations can save you from subtle issues later.

Happy coding! 🐍

--

--