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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

16 lines
Python 3.9+
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:", person)
    print("As dict:", person_dict)
    print("Type:", type(person_dict).__name__)

if __name__ == "__main__":
    main()

Output

stdout
Original namedtuple: Person(name='Alice', age=30, city='New York')
As dict: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Type: dict

How it works

The asdict function (introduced in Python 3.8 as a module-level function, previously _asdict method) converts a namedtuple into a regular dictionary where field names become keys and values are copied. It performs a shallow copy, so mutable objects inside the tuple are shared rather than duplicated. Since namedtuples are tuples, converting them to dictionaries makes it easy to pass them to functions expecting **kwargs or to serialize them as JSON. Using asdict is explicit and clearer than manual dict comprehension, and it handles the field names automatically.

Common mistakes

  • Using `_asdict()` (private method) instead of the public `asdict()` function in older code
  • Forgetting that the conversion is shallow — nested mutable objects remain shared references
  • Importing `asdict` from `collections` directly instead of using `collections.namedtuple.asdict`
  • Expecting the dict to preserve order — dicts are ordered in Python 3.7+, but field order is guaranteed by the namedtuple definition

Variations

  1. Use `person._asdict()` for compatibility with older Python versions (pre-3.8)
  2. Use a dict comprehension: `{field: getattr(person, field) for field in Person._fields}`
  3. Convert to JSON directly with `json.dumps(person_dict)` after conversion

Real-world use cases

  • Passing namedtuple data into functions that expect a dict, like `json.dumps` or `requests.post` with `data=`.
  • Serializing configuration values read from a namedtuple into a dictionary for logging or audit trails.
  • Converting database query results stored as namedtuples into dicts before sending them to a frontend API.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.