Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

1 match
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

Browse by section

Each section groups closely related Python snippets.

Dictionaries & sets — Python code examples

What you will find here

This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.