October 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Python Dictionaries: Key Facts and Practical Operations

A practical guide to Python dictionaries: create mappings, retrieve and change values, check for missing keys, iterate over entries, and understand valid keys and insertion order.
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 d[key] to look up or assign an entry, key in d to test whether a key exists, and d.items() to loop through keys and values. The examples below cover the core operations and the behaviors that matter when keys are missing or entries change.

What a Python dictionary is

A dictionary is a mutable mapping: each key identifies one value, and keys are unique within the dictionary. In this example, name and language are keys, while Ada and Python are their values:

As an Amazon Associate I earn from qualifying purchases.

person = {"name": "Ada", "language": "Python"}

If you assign a value to a key that is already present, the dictionary replaces that key’s value rather than creating a duplicate key.

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

How to create a dictionary

Use {} for an empty dictionary, a literal for known entries, or dict() when building one from keyword arguments or key-value pairs:

empty = {}
person = {"name": "Ada", "language": "Python"}
settings = dict(theme="dark", notifications=True)
from_pairs = dict([("name", "Ada"), ("language", "Python")])

A dictionary comprehension creates entries from an iterable. This one maps each number to its square:

squares = {n: n * n for n in range(4)}
# {0: 0, 1: 1, 2: 4, 3: 9}

How to retrieve, add, and change values

Use square brackets with a key to retrieve its value. Assign through the same syntax to add a new key or replace the value for an existing one:

person = {"name": "Ada"}
print(person["name"])  # Ada

person["language"] = "Python"  # add an entry
person["name"] = "Grace"       # replace the existing value

Bracket lookup is appropriate when the key is expected to exist. If it does not, Python raises a KeyError; choose a default-returning lookup or check membership when absence is normal.

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

How to handle a missing key

Use get() when a missing key should produce a fallback instead of an exception. With no second argument, d.get(key) returns None when the key is absent; with a second argument, it returns that supplied default:

person = {"name": "Ada"}
print(person.get("language"))            # None
print(person.get("language", "unknown"))  # unknown

If None might itself be a stored value, get() alone cannot tell you whether the key was absent or present with a value of None. Test membership first:

if "language" in person:
    print(person["language"])
else:
    print("No language entry")

The expression key in d checks dictionary keys, not values. To check whether a value appears, use value in d.values().

How to test for a key and remove an entry

Use in to test whether a key exists, and del to delete an entry by key:

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

if "language" in person:
    del person["language"]

Deleting a key that is not present raises KeyError, so a membership check is useful if absence is possible. del d[key] removes the entry; it does not return its value.

How to iterate through a dictionary

A for loop over a dictionary yields its keys. Use items() when each loop needs both the key and its value:

person = {"name": "Ada", "language": "Python"}

for key in person:
    print(key)

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

The methods keys(), values(), and items() provide views of the dictionary’s keys, values, and key-value pairs. These views reflect the dictionary’s contents, so they are useful for inspecting entries without making a separate list.

Which values can be dictionary keys?

Keys must have stable hash behavior while they are in the dictionary. Strings and numbers are common choices. A tuple can be a key if all of its contents are themselves suitable; a tuple containing a list, for example, is not suitable.

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

Lists and dictionaries cannot be keys because they are mutable. A value-based hash for an object that can change would not reliably identify its stored entry. Values do not have this restriction: a dictionary can store mutable values such as lists.

groups = {"admins": ["Ada", "Grace"]}
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to update or merge entries

Call update() to add entries from another mapping or an iterable of key-value pairs. When an incoming key already exists, its value replaces the current value:

profile = {"name": "Ada", "language": "Python"}
profile.update({"language": "English", "city": "London"})
# {"name": "Ada", "language": "English", "city": "London"}

What dictionary order means

Dictionary insertion order is a language guarantee in Python 3.7 and later. The official Python data model describes keys as being produced in the order they were added sequentially: Python data model reference. Python 3.6 preserved order in CPython as an implementation detail, but it was not yet a language guarantee.

Replacing the value for an existing key does not change its position. Deleting a key and adding it again places it at the end. If code depends on ordering, target Python 3.7 or later rather than relying on older implementation-specific behavior.

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.

Example: count values with a dictionary

A dictionary is useful when each item needs to be associated with a running count. This example counts how often each word appears:

words = ["apple", "pear", "apple", "plum", "pear", "apple"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)
# {"apple": 3, "pear": 2, "plum": 1}

The get(word, 0) call supplies a starting count for a word not yet seen; each pass then stores the incremented count under that word’s key.

Official Python documentation

The Python 3.14.7 tutorial explains dictionary creation and common operations in its dictionaries section. The built-in types reference documents dictionary methods and behavior.

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.