October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Python Dictionaries: A Beginner’s Guide to Creating, Using, and Updating dicts

A beginner-friendly guide to Python dictionaries: create key/value mappings, retrieve and update entries, handle missing keys, choose valid keys, and loop through dicts.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python dictionary stores values under unique keys: use a key to look up the value it identifies. Create one with braces, retrieve entries with square brackets, and use get() when a key might be missing. This guide covers the everyday patterns, safe lookups, iteration, and the rules for choosing keys.

What is a Python dictionary?

A dictionary, written dict in Python, is a mutable mapping of keys to values. Each key identifies its associated value, so you look up a dictionary entry by key rather than by numeric position.

A list is a sequence: its elements are accessed by position, such as items[0]. A dictionary instead associates unique keys with values, such as person["name"]. Both can be useful in the same program, but they represent different kinds of access. See the Python Tutorial: Data Structures.

How do I create a dictionary?

Use {} for an empty dictionary, or place comma-separated key: value pairs inside braces:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
person = {"name": "Ada", "age": 36}
empty = {}

You can also call dict() to make an empty dictionary or construct one from an iterable of key/value pairs:

scores = dict([("Mina", 92), ("Leo", 85)])

Each key appears at most once in a dictionary. If a key is repeated in a literal, its later value replaces the earlier value:

settings = {"theme": "light", "theme": "dark"}
print(settings["theme"])  # dark

How do I access and change dictionary values?

Use square brackets with a key to retrieve its value. Assign to an existing key to replace its value, or assign to a new key to add an entry:

person = {"name": "Ada", "age": 36}

print(person["name"])  # Ada
person["age"] = 37     # replace a value
person["city"] = "London"  # add an entry

To remove an entry, use del with the key:

del person["city"]

How do I avoid a KeyError?

Indexing with a key that is not in the dictionary raises KeyError. For optional data, get() returns None when the key is absent, or a fallback value you provide:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
email = person.get("email")
contact = person.get("email", "not provided")

Use in when you need to test whether a key exists before acting on it:

if "name" in person:
    print(person["name"])

These approaches answer different questions: get() retrieves a value with a fallback, while in checks key membership.

What can be a dictionary key?

Keys must be hashable so Python can find them reliably. Strings and numbers are common keys. A tuple can be a key if all of its contents are themselves suitable hashable values.

Lists and dictionaries cannot be keys because they are mutable and compared by value. A dictionary lookup depends on a key’s hash value remaining constant; changing a key in a way that affects lookup would make that unreliable. Immutability is a useful beginner clue, but the actual requirement is hashability. The Python Language Reference: Data Model explains the relationship between hashing and dictionary lookup.

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

Values do not have this restriction. A dictionary value can be a list or another dictionary:

profile = {
    "name": "Ada",
    "skills": ["Python", "math"],
    "location": {"city": "London"}
}

How do I loop through a dictionary?

A for loop over a dictionary visits its keys. Use items() to get each key and value together:

for key, value in person.items():
    print(key, value)

Use keys() for a view of the keys and values() for a view of the values. Calling list(d) produces a list of the dictionary’s keys.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I build dictionaries with comprehensions or combine them?

A dictionary comprehension creates entries from an iterable in a compact expression. This example maps each number to its square:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
squares = {n: n**2 for n in (2, 4, 6)}

You can also combine mappings with dictionary unpacking. If the same key appears more than once, a later unpacked entry supplies the value:

defaults = {"theme": "light", "font_size": 12}
custom = {"theme": "dark"}
settings = {**defaults, **custom}

print(settings)  # {'theme': 'dark', 'font_size': 12}

Are Python dictionaries ordered?

Yes. Python guarantees that dictionaries preserve insertion order from Python 3.7 onward. In CPython 3.6, insertion order was preserved as an implementation detail, rather than a language guarantee.

Insertion order is not alphabetical or numeric sorting. Replacing a value for an existing key does not change that key’s position. If you delete a key and insert it again, it goes to the end. Use sorted(d) when you specifically want sorted keys; the tutorial also distinguishes insertion order from sorting.

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.

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

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair 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.