Write a program in Python to print dataframe rows as orderDict with a list of tuple values

In Pandas, you can convert DataFrame rows to OrderedDict objects with list of tuple values. This is useful when you need to maintain the order of columns and access row data in a structured dictionary format.

Understanding the Problem

When working with DataFrames, sometimes you need each row as an OrderedDict where each column-value pair is represented as a tuple. The expected output format is ?

OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)])
OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)])
OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])

Solution Steps

To solve this problem, follow these steps ?

  • Create a DataFrame with sample data

  • Use df.itertuples(name='stud') to iterate through rows as named tuples

  • Convert each named tuple to OrderedDict using _asdict() method

  • Print the resulting OrderedDict for each row

Example

Let's implement the solution with a complete example ?

import pandas as pd

# Create sample data
students = [('Raj', 13, 'Chennai', 80),
            ('Ravi', 12, 'Delhi', 90),
            ('Ram', 13, 'Chennai', 95)]

# Create DataFrame
df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Mark'])
print("DataFrame is:")
print(df)
print()

# Convert each row to OrderedDict
for row in df.itertuples(name='stud'):
    dict_row = row._asdict()
    print(dict_row)
DataFrame is:
   Name  Age     City  Mark
0   Raj   13  Chennai    80
1  Ravi   12    Delhi    90
2   Ram   13  Chennai    95

OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)])
OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)])
OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])

How It Works

The itertuples() method creates named tuples for each row, where:

  • name='stud' sets the named tuple class name

  • _asdict() converts the named tuple to an OrderedDict

  • The 'Index' field represents the DataFrame row index

  • Column names become keys in the OrderedDict

Conclusion

Use df.itertuples(name='custom') combined with _asdict() to convert DataFrame rows into OrderedDict objects. This approach preserves column order and provides easy access to row data as key-value pairs.

Updated on: 2026-03-25T16:27:51+05:30

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements