Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

3 matches
Dictionaries & sets easy

Convert namedtuple to dict with asdict in Python

Convert a namedtuple instance into an ordinary dictionary using the asdict function from the collections module's namedtuple utility.

namedtuple dict asdict
Python
from collections import namedtuple, asdict

def main():
    # Define a namedtuple for a person
    Person = namedtuple("Person", ["name", "age", "city"])
    person = Person(name="Alice", age=30, city="New York")
    
    # Convert namedtuple to dict
    person_dict = asdict(person)
    
    print("Original namedtuple…
12 0 Open
OOP & classes easy

How to Use NamedTuples for Lightweight Records in Python

Create lightweight, immutable data records with namedtuple that behave like tuples but have named fields for improved readability and access.

namedtuple tuples records
Python
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

p = Point(3, 4)
print(p)
print(p.x, p.y)
print(p[0], p[1])

x, y = p
print(x, y)

print(p._asdict())

p2 = p._replace(x=10)
print(p2)

if __name__ == "__main__":
    print("NamedTuple demo complete")
14 0 Open
Testing & modern typing easy

NamedTuple typed record in Python

Define a lightweight immutable record with type hints using typing.NamedTuple; access fields by name and unpack like a tuple.

namedtuple typing records
Python
from typing import NamedTuple


class Point(NamedTuple):
    x: float
    y: float
    label: str = "origin"


if __name__ == "__main__":
    p = Point(3.5, -2.0, "A")
    print(p)
    print(f"x={p.x}, y={p.y}, label={p.label}")
    print("is tuple:", isinstance(p, tuple))

    q = Point(1.0, 1.0)
    print(q)

    # …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.