DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Initialize a Dictionary in Python: Keys, Values, Zeros, and Defaults

Create Python dictionaries with {}, literals, dict(), comprehensions, or dict.fromkeys(). Learn when zero-filled keys, mutable defaults, and get() behave differently.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use {} to create an empty dictionary, a dictionary literal for known key-value pairs, and a comprehension or dict.fromkeys() to initialize a set of keys. For separate mutable values such as lists, use a comprehension. If you only need a fallback when reading a possibly absent key, use get()—it does not add the key to the dictionary.

Start with an empty dictionary or known values

In Python 3.14, {} creates an empty dictionary. To start with entries, put comma-separated key: value pairs inside braces:

settings = {}
user = {"name": "Ada", "active": True}

Use a literal when the keys and values are known and you want the mapping to be easy to read at a glance. The official Python data structures tutorial documents dictionary literals and creation patterns.

Braces alone create a dictionary, not an empty set. To create an empty set, write set().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a dictionary with dict()

The dict() constructor can make an empty dictionary or build one from a mapping, an iterable of key-value pairs, or keyword arguments. Use it when your input already has one of those forms:

empty = dict()
scores = dict([("Ada", 10), ("Lin", 12)])
options = dict(theme="dark", compact=True)

If construction supplies the same key more than once, the later value replaces the earlier one. For example, dict([("Ada", 10), ("Ada", 11)]) produces {"Ada": 11}. The constructor’s accepted inputs and duplicate-key behavior are covered in the Python 3.14 built-in types reference.

Initialize keys with zero or another shared value

For a range of generated integer keys, use a dictionary comprehension. For an existing iterable of keys that should all start with the same immutable value, dict.fromkeys() is concise.

Generate keys with a comprehension

zeros = {i: 0 for i in range(5)}

This creates keys 0 through 4, each associated with the integer 0. Change the expression after the colon to produce a different initial value for each key.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use dict.fromkeys() for one common value

flags = dict.fromkeys(["draft", "review", "published"], False)

Each key receives the same value reference. This is suitable for immutable values such as integers, booleans, or strings. The behavior of fromkeys() is specified in the Python built-in types reference.

Create distinct mutable defaults for each key

Do not use dict.fromkeys(keys, []) when each key needs its own list. Every entry would refer to the same list, so appending through one key would also appear through the others. Create a new value for each key with a comprehension instead:

buckets = {name: [] for name in ["red", "blue", "green"]}
buckets["red"].append("apple")

# Only the red bucket contains "apple".

The same rule applies to other mutable values, such as dictionaries or sets: construct a fresh object inside the comprehension for each key. Python’s built-in types reference describes dict.fromkeys() as assigning the same value to each key.

Choose the initializer that fits the data

Situation Use Example
No entries yet Empty literal or constructor {} or dict()
Small, fixed set of known pairs Dictionary literal {"name": "Ada"}
Input is a mapping or key-value pairs dict() dict([("Ada", 10)])
Keys or values come from an expression Dictionary comprehension {i: 0 for i in range(5)}
Every key needs the same immutable value dict.fromkeys() dict.fromkeys(keys, 0)
Every key needs a separate mutable value Dictionary comprehension {key: [] for key in keys}
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use get() to read with a fallback, not to initialize

When a key may be absent and you only need a fallback for that lookup, call d.get(key, default). If the key is missing and no default is supplied, get() returns None; with a default, it returns that value instead of raising KeyError.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
settings = {}
mode = settings.get("mode", "standard")
# settings is still empty; "mode" was not inserted.

Use assignment, such as settings["mode"] = "standard", if the key should actually be stored. The Python data structures tutorial and built-in types reference distinguish lookup with get() from adding an entry.

Check key and ordering behavior

  • Dictionary keys must be hashable. A list is mutable and unhashable, so it cannot be used as a key.
  • Assigning a value to a key that is already present replaces that key’s previous value.
  • Python dictionaries preserve insertion order, as documented in the Python 3.14 built-in types reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.