Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions python-data-structures/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Common Python Data Structures (Guide)

This folder provides the code examples for the Real Python tutorial [Common Python Data Structures (Guide)](https://realpython.com/python-data-structures/).

## Setup

The examples use only the Python standard library, so there's nothing to install. You need Python 3.7 or later.

## Usage

Each script covers one section of the tutorial:

- `dictionaries.py`: Dictionaries, maps, and hash tables
- `arrays.py`: Array data structures
- `records.py`: Records, structs, and data transfer objects
- `sets.py`: Sets and multisets
- `stacks.py`: Stacks (LIFOs)
- `queues.py`: Queues (FIFOs)
- `priority_queues.py`: Priority queues

Run any of them with Python:

```sh
$ python dictionaries.py
```
91 changes: 91 additions & 0 deletions python-data-structures/arrays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import array

# list: Mutable dynamic arrays
arr = ["one", "two", "three"]
print(arr[0])
print(arr)
arr[1] = "hello"
print(arr)
del arr[1]
print(arr)
# Lists can hold arbitrary data types:
arr.append(23)
print(arr)

# tuple: Immutable containers
arr = ("one", "two", "three")
print(arr[0])
print(arr)
try:
arr[1] = "hello"
except TypeError as error:
print(f"TypeError: {error}")
# Adding elements creates a copy of the tuple:
print(arr + (23,))

# array.array: Basic typed arrays
arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
print(arr[1])
print(arr)
arr[1] = 23.0
print(arr)
del arr[1]
print(arr)
arr.append(42.0)
print(arr)
# Arrays are "typed":
try:
arr[1] = "hello"
except TypeError as error:
print(f"TypeError: {error}")

# str: Immutable arrays of Unicode characters
arr = "abcd"
print(repr(arr[1]))
print(repr(arr))
try:
arr[1] = "e"
except TypeError as error:
print(f"TypeError: {error}")
# Strings can be unpacked into a list to get a mutable representation:
print(list("abcd"))
print(repr("".join(list("abcd"))))
# Strings are recursive data structures:
print(type("abc"))
print(type("abc"[0]))

# bytes: Immutable arrays of single bytes
arr = bytes((0, 1, 2, 3))
print(arr[1])
# Bytes literals have their own syntax:
print(arr)
arr = b"\x00\x01\x02\x03"
# Only valid bytes are allowed:
try:
bytes((0, 300))
except ValueError as error:
print(f"ValueError: {error}")
try:
arr[1] = 23
except TypeError as error:
print(f"TypeError: {error}")

# bytearray: Mutable arrays of single bytes
arr = bytearray((0, 1, 2, 3))
print(arr[1])
print(arr)
arr[1] = 23
print(arr)
print(arr[1])
# Bytearrays can grow and shrink in size:
del arr[1]
print(arr)
arr.append(42)
print(arr)
# Bytearrays can only hold bytes (integers in the range 0 <= x <= 255):
try:
arr[1] = 300
except ValueError as error:
print(f"ValueError: {error}")
# Bytearrays can be converted back into bytes objects (this copies the data):
print(bytes(arr))
55 changes: 55 additions & 0 deletions python-data-structures/dictionaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from collections import ChainMap, OrderedDict, defaultdict
from types import MappingProxyType

# dict: Your go-to dictionary
phonebook = {
"bob": 7387,
"alice": 3719,
"jack": 7052,
}
squares = {x: x * x for x in range(6)}
print(phonebook["alice"])
print(squares)

# collections.OrderedDict: Remember the insertion order of keys
d = OrderedDict(one=1, two=2, three=3)
print(d)
d["four"] = 4
print(d)
print(d.keys())

# collections.defaultdict: Return default values for missing keys
dd = defaultdict(list)
# Accessing a missing key creates it and initializes it
# using the default factory, list() in this example:
dd["dogs"].append("Rufus")
dd["dogs"].append("Kathrin")
dd["dogs"].append("Mr Sniffles")
print(dd["dogs"])

# collections.ChainMap: Search multiple dictionaries as a single mapping
dict1 = {"one": 1, "two": 2}
dict2 = {"three": 3, "four": 4}
chain = ChainMap(dict1, dict2)
print(chain)
# ChainMap searches each collection in the chain
# from left to right until it finds the key (or fails):
print(chain["three"])
print(chain["one"])
try:
chain["missing"]
except KeyError as error:
print(f"KeyError: {error}")

# types.MappingProxyType: A wrapper for making read-only dictionaries
writable = {"one": 1, "two": 2}
read_only = MappingProxyType(writable)
# The proxy is read-only:
print(read_only["one"])
try:
read_only["one"] = 23
except TypeError as error:
print(f"TypeError: {error}")
# Updates to the original are reflected in the proxy:
writable["one"] = 42
print(repr(read_only))
32 changes: 32 additions & 0 deletions python-data-structures/priority_queues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import heapq
from queue import PriorityQueue

# list: Manually sorted queues
q = []
q.append((2, "code"))
q.append((1, "eat"))
q.append((3, "sleep"))
# Remember to re-sort every time a new element is inserted,
# or use bisect.insort()
q.sort(reverse=True)
while q:
next_item = q.pop()
print(next_item)

# heapq: List-based binary heaps
q = []
heapq.heappush(q, (2, "code"))
heapq.heappush(q, (1, "eat"))
heapq.heappush(q, (3, "sleep"))
while q:
next_item = heapq.heappop(q)
print(next_item)

# queue.PriorityQueue: Beautiful priority queues
q = PriorityQueue()
q.put((2, "code"))
q.put((1, "eat"))
q.put((3, "sleep"))
while not q.empty():
next_item = q.get()
print(next_item)
53 changes: 53 additions & 0 deletions python-data-structures/queues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from collections import deque
import multiprocessing
from queue import Empty, Queue

# list: Terribly sloooow queues
q = []
q.append("eat")
q.append("sleep")
q.append("code")
print(q)
# Careful: This is slow!
print(q.pop(0))

# collections.deque: Fast and robust queues
q = deque()
q.append("eat")
q.append("sleep")
q.append("code")
print(q)
print(q.popleft())
print(q.popleft())
print(q.popleft())
try:
q.popleft()
except IndexError as error:
print(f"IndexError: {error}")

# queue.Queue: Locking semantics for parallel computing
q = Queue()
q.put("eat")
q.put("sleep")
q.put("code")
print(q)
print(q.get())
print(q.get())
print(q.get())
try:
q.get_nowait()
except Empty:
print("queue.Empty")
# Calling q.get() now would block and wait forever.

# multiprocessing.Queue: Shared job queues
if __name__ == "__main__":
q = multiprocessing.Queue()
q.put("eat")
q.put("sleep")
q.put("code")
print(q)
print(q.get())
print(q.get())
print(q.get())
# Calling q.get() now would block and wait forever.
117 changes: 117 additions & 0 deletions python-data-structures/records.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
from collections import namedtuple
from dataclasses import dataclass
import dis
from struct import Struct
from sys import getsizeof
from types import SimpleNamespace
from typing import NamedTuple

# dict: Simple data objects
car1 = {
"color": "red",
"mileage": 3812.4,
"automatic": True,
}
car2 = {
"color": "blue",
"mileage": 40231,
"automatic": False,
}
print(car2)
print(car2["mileage"])
car2["mileage"] = 12
car2["windshield"] = "broken"
print(car2)

# tuple: Immutable groups of objects
dis.dis(compile("(23, 'a', 'b', 'c')", "", "eval"))
dis.dis(compile("[23, 'a', 'b', 'c']", "", "eval"))

# Fields: color, mileage, automatic
car1 = ("red", 3812.4, True)
car2 = ("blue", 40231.0, False)
print(car1)
print(car2)
print(car2[1])


# Write a custom class: More work, more control
class Car:
def __init__(self, color, mileage, automatic):
self.color = color
self.mileage = mileage
self.automatic = automatic


car1 = Car("red", 3812.4, True)
car2 = Car("blue", 40231.0, False)
print(car2.mileage)
car2.mileage = 12
car2.windshield = "broken"
# The string representation isn't very useful:
print(car1)


# dataclasses.dataclass: Python 3.7+ data classes
@dataclass
class Car:
color: str
mileage: float
automatic: bool


car1 = Car("red", 3812.4, True)
print(car1)
print(car1.mileage)
car1.mileage = 12
car1.windshield = "broken"
# Type annotations aren't enforced without a type checker like mypy:
print(Car("red", "NOT_A_FLOAT", 99))

# collections.namedtuple: Convenient data objects
p1 = namedtuple("Point", "x y z")(1, 2, 3)
p2 = (1, 2, 3)
print(getsizeof(p1))
print(getsizeof(p2))

Car = namedtuple("Car", "color mileage automatic")
car1 = Car("red", 3812.4, True)
print(car1)
print(car1.mileage)
try:
car1.mileage = 12
except AttributeError as error:
print(f"AttributeError: {error}")


# typing.NamedTuple: Improved namedtuples
class Car(NamedTuple):
color: str
mileage: float
automatic: bool


car1 = Car("red", 3812.4, True)
print(car1)
print(car1.mileage)
try:
car1.windshield = "broken"
except AttributeError as error:
print(f"AttributeError: {error}")
print(Car("red", "NOT_A_FLOAT", 99))

# struct.Struct: Serialized C structs
MyStruct = Struct("i?f")
data = MyStruct.pack(23, False, 42.0)
# All you get is a blob of data:
print(data)
# Data blobs can be unpacked again:
print(MyStruct.unpack(data))

# types.SimpleNamespace: Fancy attribute access
car1 = SimpleNamespace(color="red", mileage=3812.4, automatic=True)
print(car1)
car1.mileage = 12
car1.windshield = "broken"
del car1.automatic
print(car1)
Loading
Loading