Dictionaries

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

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"])
# 1
print(d1.get("b"))
# 2
print(d1.get("z", 0))
# 0, default if key not found

# add new key-value
d1["d"] = 4

# update existing key
d1["a"] = 10

# remove key
del d1["b"]




Built-in functions used with dictionaries

The following built in functions can be used with dictionaries:

  • len(d) → number of key-value pairs
  • in → check if key exists
  • all(d) → True if all keys are truthy
  • any(d) → True if any key is truthy
  • sorted(d) → returns sorted list of keys

Example:

d = {"a": 1, "b": 0, "": 3}

# len(d) → number of key-value pairs
print("len(d):", len(d))
# 3

# in → check if key exists
print("'a' in d:", "a" in d)
# True
print("'z' in d:", "z" in d)
# False

# all(d) → True if all keys are truthy
# Here we have an empty string "" as a key → falsy
print("all(d):", all(d))
# False

# any(d) → True if any key is truthy
print("any(d):", any(d))
# True, because "a" and "b" are truthy keys

# sorted(d) → returns sorted list of keys
print("sorted(d):", sorted(d))
# ['', 'a', 'b']




Dictionaries own functions

Function

Description

dict.keys()

Returns a view of all keys

dict.values()

Returns a view of all values

dict.items()

Returns a view of key-value pairs

dict.get(key, default)

Returns value if key exists, else default

dict.pop(key)

Remove key and return value

dict.popitem()

Remove and return last inserted item

dict.clear()

Remove all items

dict.update(other)

Update dictionary with key-values from another dict or iterable

dict.copy()

Return a shallow copy

dict.setdefault(key, default)

Return value if key exists; else insert key with default


Examples:

# Dictionary Methods Demo
d = {"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"))
# 1
print("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"])) → raises ValueError
  • Non-iterables (e.g., dict(42)) → raises TypeError
  • Sequences of wrong-sized elements (must be length 2) → raises ValueError

Examples:

# Existing dictionaries
dict({"a": 1, "b": 2})
# {'a': 1, 'b': 2}

# Keyword arguments
dict(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 iterables
keys = ["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)
# True

Ordering (<, >, 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 tuples




Dictionary 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 comprehension
squares = {x: x**2 for x in nums}
print("Number -> Square:", squares)

# ----------------------------------------
# Filtering items
evens = {x: x**2 for x in nums if x % 2 == 0}
print("Even -> Square:", evens)

# ----------------------------------------
# Conditional expressions
labels = {x: ("even" if x % 2 == 0 else "odd") for x in nums}
print("Number -> Even/Odd label:", labels)

# ----------------------------------------
# Transforming strings
word = "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 comprehension
pairs = {(x, y): x * y for x in range(1, 4) for y in range(1, 4)}
print("Pairs -> Product:", pairs)

# ----------------------------------------
# Swapping keys and values
fruit_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 condition
student_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 functions
def cube(x): return x**3
cubes = {x: cube(x) for x in nums}
print("Number -> Cube:", cubes)

# ----------------------------------------
# Real-world example: word count
text = "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-value
d1["a"] = 10
# update existing
print("After add/update:", d1)

del d1["b"]
# delete key
print("After del 'b':", d1)

val = d1.pop("c")
# remove and return value
print("pop('c'):", val, "| dict now:", d1)

d1.update({"e": 50, "f": 60})
# add multiple
print("After update:", d1)

d1.setdefault("g", 70)
# insert only if key doesn't exist
print("After setdefault('g', 70):", d1)

d1_copy = d1.copy()
# shallow copy
print("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 item
print("popitem():", last_item, "| dict now:", d)

# --- Built-in functions ---
print("Length:", len(d))
# 2 after popitem
print("'a' in d:", 'a' in d)
# True
print("All keys truthy?", all(d))
# True
print("Any key truthy?", any(d))
# True
print("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))

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact