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

Python dictionaries store unique, hashable keys mapped to values, and preserve insertion order in Python 3.7 and later. The methods you’ll use most often help you look up values safely, inspect entries, add or remove data, and copy or combine mappings. This guide covers ten practical methods and shows when each changes the original dictionary.

Quick comparison of the 10 dictionary methods

Method Changes original? Returns Missing-key behavior Common use
clear() Yes None Not applicable Empty an existing dictionary
copy() No A shallow copy Not applicable Make a separate top-level mapping
dict.fromkeys() No A new dictionary Not applicable Initialize a set of keys to one value
get() No The value or a default Returns the default, or None if omitted Look up an optional key safely
items() No A dynamic view of key-value pairs Not applicable Iterate over keys and values together
keys() No A dynamic view of keys Not applicable Inspect or iterate over keys
pop() Yes The removed value Raises KeyError unless a default is given Remove a named key and retrieve its value
popitem() Yes The removed key-value pair Raises KeyError if empty Remove the most recently added entry
setdefault() Sometimes The existing or inserted value Inserts the default for an absent key Initialize a missing entry
update() Yes None Not applicable Apply one or more sets of key-value changes

In the examples below, mutating methods change the existing dictionary object. Views from keys(), values(), and items() reflect later changes to their dictionary; they are not detached lists.

Read and inspect dictionary data

get(): retrieve a value with a fallback

Indexing with square brackets is appropriate when the key is required: config["port"] raises KeyError if the key is absent. For optional keys, get() returns a fallback instead:

config = {"host": "localhost"}
port = config.get("port", 8000)
print(port)  # 8000

If you leave out the second argument, a missing key returns None. The dictionary is not changed.

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

items(): iterate over keys and values

Use items() when a loop needs both parts of each entry. It provides a dynamic view of key-value pairs:

scores = {"Mina": 92, "Leo": 85}
for name, score in scores.items():
    print(name, score)

keys(): inspect keys

keys() provides a dynamic view of the dictionary’s keys. For a membership check, test the dictionary directly: "admin" in users checks whether "admin" is a key and is shorter than "admin" in users.keys().

values(): inspect values

values() provides a dynamic view of the values. For example, if 0 in scores.values(): tests whether a value of 0 is present. Like the other dictionary views, it is not a list; make a list explicitly with list(scores.values()) if you need a separate snapshot.

Add, remove, or reset entries

clear(): empty the existing dictionary

clear() removes every entry in place and returns None. Use it when other parts of your program hold a reference to the same dictionary and should see it emptied.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
settings = {"theme": "dark", "lang": "en"}
settings.clear()
print(settings)  # {}

pop(): remove a named entry and get its value

pop(key) deletes the named entry and returns its value. If the key may be absent, pass a fallback as the second argument to avoid KeyError:

config = {"timeout": 45}
timeout = config.pop("timeout", 30)
print(timeout)  # 45
print(config)   # {}

If "timeout" were missing, this example would return 30 and leave the dictionary unchanged.

popitem(): remove the newest entry

In current Python, popitem() removes and returns the last-in, first-out (LIFO) key-value pair: the entry most recently added. It raises KeyError if the dictionary is empty.

cache = {"first": 1, "second": 2}
key, value = cache.popitem()
print(key, value)  # second 2

Check that the dictionary is nonempty before calling it when an empty mapping is possible.

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

setdefault(): get a value or initialize a missing key

setdefault(key, default) returns the current value when the key exists. When the key is missing, it inserts default and returns that value; it does not overwrite an existing entry.

groups = {}
groups.setdefault("python", []).append("dict")
print(groups)  # {'python': ['dict']}

This can be handy for collecting values under keys. When initialization needs to be especially clear, an explicit membership check and assignment may be easier to read.

update(): apply changes to the dictionary

update() mutates the dictionary and returns None. It accepts another mapping, an iterable of key-value pairs, and keyword arguments. If an incoming key already exists, its value is replaced.

profile = {"role": "writer", "active": False}
profile.update({"role": "editor"}, active=True)
print(profile)  # {'role': 'editor', 'active': True}

Create or combine dictionaries

copy(): make a shallow copy

copy() creates a new top-level dictionary. Changes to its top-level keys do not alter the original, but nested mutable objects are still shared because the copy is shallow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
original = {"tags": ["python"]}
clone = original.copy()
clone["name"] = "guide"       # top-level change only in clone
clone["tags"].append("dict")  # shared nested list changes in both

For independent nested mutable data, use copy.deepcopy() from the standard-library copy module, keeping in mind that deep-copy behavior can depend on the objects involved.

dict.fromkeys(): initialize keys to one value

dict.fromkeys(iterable, value) creates a new dictionary with each supplied key mapped to the same value. If the value is mutable, every key refers to that same object:

fields = dict.fromkeys(["name", "email"], "")
shared = dict.fromkeys(["red", "blue"], [])
shared["red"].append("item")
print(shared)  # both values refer to the same list

Use a comprehension when each key needs its own mutable value:

independent = {color: [] for color in ["red", "blue"]}

Merge with | or |= (Python 3.9+)

Python 3.9 added dictionary merge operators. The | operator creates a new dictionary, while |= updates the dictionary on its left in place. When both dictionaries contain the same key, the value from the right-hand operand wins.

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.
defaults = {"theme": "light", "lang": "en"}
custom = {"theme": "dark"}
merged = defaults | custom
print(merged)  # {'theme': 'dark', 'lang': 'en'}

defaults |= custom  # changes defaults in place
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Dictionary behavior that matters across these methods

  • A dictionary stores unique key-value pairs. Keys must be hashable; values can be of any type. Python’s tutorial describes a dictionary as “a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).”
  • Insertion order is guaranteed starting with Python 3.7. Dictionaries became reversible in Python 3.8, so reverse iteration follows the reverse of insertion order.
  • keys(), values(), and items() return dynamic views. Convert a view to a list if you need a detached snapshot.
  • Methods such as clear(), pop(), popitem(), setdefault(), and update() can mutate the original dictionary. copy(), dict.fromkeys(), and | produce new dictionaries.

For full language-reference details, see the Python tutorial’s dictionary section and the Python library reference for mapping types.

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.