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


Assume, you have a dataframe and the result for orderDict with list of tuples are −

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

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Set for loop to access all the rows using df.itertuples() function inside set name=’stud’

for row in df.itertuples(name='stud')
  • Convert all the rows to orderDict with list of tuples using rows._asdict() function and save it as dict_row. Finally print the values,

dict_row = row._asdict()
print(dict_row)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
Students = [('Raj', 13, 'Chennai', 80) ,
            ('Ravi', 12, 'Delhi' , 90) ,
            ('Ram', 13, 'Chennai', 95)]
df = pd.DataFrame(Students, columns=['Name', 'Age', 'City', 'Mark'])
print("DataFrame is:\n",df)
for row in df.itertuples(name='stud'):
   dict_row = row._asdict()
   print(dict_row)

Output

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)])

Updated on: 25-Feb-2021

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements