Dictionaries
Python - A Quick Start for existing Programers
2 min read
Published Sep 16 2025, updated Aug 17 2026
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:
d1 = {"a": 1, "b": 2, "c": 3}print(d1["a"]) # 1print(d1.get("b")) # 2print(d1.get("z", 0)) # 0, default if key not found# add new key-valued1["d"] = 4 # update existing keyd1["a"] = 10 # remove keydel d1["b"]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:
d = {"a": 1, "b": 0, "": 3}# len(d) → number of key-value pairsprint("len(d):", len(d)) # 3# in → check if key existsprint("'a' in d:", "a" in d) # Trueprint("'z' in d:", "z" in d) # False# all(d) → True if all keys are truthy# Here we have an empty string "" as a key → falsyprint("all(d):", all(d)) # False# any(d) → True if any key is truthyprint("any(d):", any(d)) # True, because "a" and "b" are truthy keys# sorted(d) → returns sorted list of keysprint("sorted(d):", sorted(d)) # ['', 'a', 'b']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:
# Dictionary Methods Demod = {"a": 1, "b": 2, "c": 3}# keys(), values(), items()print("Keys:", d.keys()) # dict_keys(['a', 'b', 'c'])print("Values:", d.values()) # dict_values([1, 2, 3])print("Items:", d.items()) # dict_items([('a', 1), ('b', 2), ('c', 3)])# get(key, default)print("get('a'):", d.get("a")) # 1print("get('z', 0):", d.get("z", 0)) # 0 (default)# pop(key)val = d.pop("b")print("pop('b'):", val, "| dict now:", d) # 2, dict without 'b'# popitem() (removes last inserted item)key, val = d.popitem()print("popitem():", (key, val), "| dict now:", d)# setdefault(key, default)print("setdefault('x', 42):", d.setdefault("x", 42))print("After setdefault:", d)# update(other)d.update({"y": 100, "z": 200})print("After update:", d)# copy()d_copy = d.copy()print("Copy of dict:", d_copy)# clear()d.clear()print("After clear:", d)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:
# Existing dictionariesdict({"a": 1, "b": 2}) # {'a': 1, 'b': 2}# Keyword argumentsdict(a=1, b=2) # {'a': 1, 'b': 2}# Sequence of pairs (iterable of 2-element iterables)dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}dict([["x", 10], ["y", 20]]) # {'x': 10, 'y': 20}# Zipped iterableskeys = ["a", "b", "c"]values = [1, 2, 3]dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}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.
d1 = {"a": 1, "b": 2}d2 = {"b": 2, "a": 1}d3 = {"a": 1, "b": 3}print(d1 == d2) # True (same key-value pairs, order irrelevant)print(d1 == d3) # False (value for 'b' differs)print(d1 != d3) # TrueOrdering (<, >, etc.) is NOT Supported
d1 = {"a": 1}d2 = {"a": 2}print(d1 < d2) # TypeError: '<' not supported between instances of 'dict' and 'dict'If you need ordering, you must compare something derived from the dict, like its keys, items, or values:
print(sorted(d1.items()) < sorted(d2.items())) # Works, compares lists of tuplesDictionary comprehension
- Similar to list/set comprehensions, but produces a dict
{key: value}. - Keys must be unique (later values overwrite earlier ones).
Syntax:
{key_expr: value_expr for item in iterable if condition}Benefits:
- Build dictionaries concisely.
- Transform one mapping into another.
- Filter keys/values easily.
- Avoid writing long loops for dict creation.
Examples:
nums = [1, 2, 3, 4, 5]# ----------------------------------------# Basic dict comprehensionsquares = {x: x**2 for x in nums}print("Number -> Square:", squares)# ----------------------------------------# Filtering itemsevens = {x: x**2 for x in nums if x % 2 == 0}print("Even -> Square:", evens)# ----------------------------------------# Conditional expressionslabels = {x: ("even" if x % 2 == 0 else "odd") for x in nums}print("Number -> Even/Odd label:", labels)# ----------------------------------------# Transforming stringsword = "comprehension"char_map = {ch: ord(ch) for ch in word}print("Char -> ASCII code:", char_map)# Deduplicate automatically (dict keys must be unique)upper_map = {ch.lower(): ch.upper() for ch in word}print("Lower -> Upper (unique keys):", upper_map)# ----------------------------------------# Nested loops in dict comprehensionpairs = {(x, y): x * y for x in range(1, 4) for y in range(1, 4)}print("Pairs -> Product:", pairs)# ----------------------------------------# Swapping keys and valuesfruit_prices = {"apple": 1.2, "banana": 0.5, "pear": 0.8}swapped = {price: fruit for fruit, price in fruit_prices.items()}print("Price -> Fruit:", swapped)# ----------------------------------------# Complex conditionstudent_scores = {"Alice": 85, "Bob": 60, "Charlie": 95}passed = {name: score for name, score in student_scores.items() if score >= 70}print("Passed students:", passed)# ----------------------------------------# Using functionsdef cube(x): return x**3cubes = {x: cube(x) for x in nums}print("Number -> Cube:", cubes)# ----------------------------------------# Real-world example: word counttext = "the quick brown fox jumps over the lazy dog the fox"word_count = {word: text.split().count(word) for word in set(text.split())}print("Word counts:", word_count)Full demonstration of dictionaries
# --- Creating dictionaries ---empty = {}d1 = {"a": 1, "b": 2, "c": 3}d2 = dict(x=10, y=20)nested = {"Alice": {"phone": "123", "email": "alice@example.com"}}print("Empty dict:", empty)print("d1:", d1)print("d2:", d2)print("Nested dict:", nested)# --- Accessing values ---print("d1['a']:", d1["a"])print("d1.get('b'):", d1.get("b"))print("d1.get('z', 0):", d1.get("z", 0)) # default# --- Modifying dictionaries ---d1["d"] = 4 # add new key-valued1["a"] = 10 # update existingprint("After add/update:", d1)del d1["b"] # delete keyprint("After del 'b':", d1)val = d1.pop("c") # remove and return valueprint("pop('c'):", val, "| dict now:", d1)d1.update({"e": 50, "f": 60}) # add multipleprint("After update:", d1)d1.setdefault("g", 70) # insert only if key doesn't existprint("After setdefault('g', 70):", d1)d1_copy = d1.copy() # shallow copyprint("Copy:", d1_copy)d1.clear()print("After clear:", d1)# --- Dictionary Methods Demo on new dict ---d = {"a": 1, "b": 2, "c": 3}print("Keys:", d.keys())print("Values:", d.values())print("Items:", d.items())last_item = d.popitem() # removes last inserted itemprint("popitem():", last_item, "| dict now:", d)# --- Built-in functions ---print("Length:", len(d)) # 2 after popitemprint("'a' in d:", 'a' in d) # Trueprint("All keys truthy?", all(d)) # Trueprint("Any key truthy?", any(d)) # Trueprint("Sorted keys:", sorted(d)) # ['b', 'c']# --- Iterating over dictionaries ---for k in d: print("Key:", k)for k, v in d.items(): print("Key-Value:", k, v)for v in d.values(): print("Value:", v)# --- Nested and complex dictionaries ---grades = {"Alice": [90, 85], "Bob": [75, 80]}print("Grades:", grades)contacts = { "Alice": {"phone": "123", "email": "alice@example.com"}, "Bob": {"phone": "456", "email": "bob@example.com"}}print("Contacts:", contacts)# --- Dictionary comprehension ---squares = {x: x**2 for x in range(5)}print("Squares dict:", squares)# --- Using dictionaries in loops ---for student, scores in grades.items(): print(student, "average:", sum(scores)/len(scores))