
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How can I convert a Python Named tuple to a dictionary?
Namedtuple class is defined in the collections module. It returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. The constructor takes type name and field list as arguments. For example, a student namedtuple is declared as follows −
>>> from collections import namedtuple >>> student=namedtuple("student","name, age, marks")
The object of this namedtuple class is declared as −
>>> s1=student("Raam",21,45)
This class has _asdict() method which returns orderdict() object
>>> d=s1._asdict() >>> d OrderedDict([('name', 'Raam'), ('age', 21), ('marks', 45)])
To obtain regular dictionary object use dict() function
>>> dct=dict(d) >>> dct {'name': 'Raam', 'age': 21, 'marks': 45}
Good
- Related Articles
- How I can convert a Python Tuple into Dictionary?
- How can I convert a Python tuple to string?
- How can I convert a Python tuple to an Array?
- How can I convert Python tuple to C array?
- How can I convert Python strings into tuple?
- How can I convert Python dictionary to JavaScript hash table?
- Convert tuple to adjacent pair dictionary in Python
- How we can create a dictionary from a given tuple in Python?
- How can I append a tuple into another tuple in Python?
- Convert Nested Tuple to Custom Key Dictionary in Python
- How can I subtract tuple of tuples from a tuple in Python?
- How can I create a non-literal python tuple?
- How to convert Python Dictionary to a list?
- How to convert a spreadsheet to Python dictionary?
- How can I convert bytes to a Python string?

Advertisements