Dictionaries
Python - A Quick Start for existing Programers
2 min read
Published Sep 16 2025, updated Sep 30 2025
Guide Sections
Guide Comments
A dictionary in Python is a mutable collection of key-value pairs.
- Keys must be unique and hashable (strings, numbers, tuples of immutable elements, etc.).
- Values can be any type and can be duplicated.
- Dictionaries are mutable, so you can add, remove, or update items.
Example:
Built-in functions used with dictionaries
The following built in functions can be used with dictionaries:
len(d)→ number of key-value pairsin→ check if key existsall(d)→ True if all keys are truthyany(d)→ True if any key is truthysorted(d)→ returns sorted list of keys
Example:
Dictionaries own functions
Function | Description |
| Returns a view of all keys |
| Returns a view of all values |
| Returns a view of key-value pairs |
| Returns value if key exists, else default |
| Remove key and return value |
| Remove and return last inserted item |
| Remove all items |
| Update dictionary with key-values from another dict or iterable |
| Return a shallow copy |
| Return value if key exists; else insert key with default |
Examples:
Casting to a dictionary
You can call dict(x) to create a dictionary, but the rules are stricter than for list() or tuple()
Does NOT Work With:
- Single iterables of keys only (e.g.,
dict(["a", "b"])) → raisesValueError - Non-iterables (e.g.,
dict(42)) → raisesTypeError - Sequences of wrong-sized elements (must be length 2) → raises
ValueError
Examples:
Dictionary comparisons
Unlike lists and tuples, dictionaries do not support ordering comparisons (<, >, <=, >=).
They only support equality (==) and inequality (!=).
Equality (==) and Inequality (!=)
- Two dictionaries are equal if they have the same keys with the same values (order does not matter).
- Inequality (
!=) is the logical opposite.
Ordering (<, >, etc.) is NOT Supported
If you need ordering, you must compare something derived from the dict, like its keys, items, or values:
Dictionary comprehension
- Similar to list/set comprehensions, but produces a dict
{key: value}. - Keys must be unique (later values overwrite earlier ones).
Syntax:
Benefits:
- Build dictionaries concisely.
- Transform one mapping into another.
- Filter keys/values easily.
- Avoid writing long loops for dict creation.
Examples:














