user11308594
user11308594

Reputation:

Rearrange Fields in Python

I am trying to make my python program display the name of the employee, salary, and department in a list. Here is my csv file:

Name, Salary, Department
Pika Chu, 5000, Pokemon
Peter Parker, 10000, Friendly Neighborhood Spiderman
Bruce Lee, 25000, Kung Fu Master
Trevor Phillips, 30000, Grand Theft Auto
Willy Wonka, 1000000, Chocolatier
Mario, 84000, Plumber
Sonic, 20000, Runner

And here is my code:


#!/usr/bin/env python3
import csv
import os



def read_employees(file):


 open(file, 'r')


 csv.register_dialect('stfDialect', skipinitialspace=True, strict=True)
 staffFile = csv.DictReader(open(file), dialect = 'stfDialect')

 staffList = []
 for data in staffFile:
     staffList.append(data)
 return staffList

staffList = read_employees("Staff.csv")
print(staffList)

The output is this:

{'Name': 'Pika Chu', 'Salary': '5000', 'Department': 'Pokemon'}

But I want the output to display the data like this:

{'Department': 'Pokemon', 'Salary': '5000', 'Name': 'Pika Chu'}

May I know how I can make this happen? Thank you very much!

Upvotes: 0

Views: 88

Answers (2)

Błotosmętek
Błotosmętek

Reputation: 12927

import csv
import os
def read_employees(file):
  csv.register_dialect('stfDialect', skipinitialspace=True, strict=True)
  with open(file, r') as f
    staffFile = csv.DictReader(f, dialect = 'stfDialect')
  return list(staffFile)

staffList = read_employees("Staff.csv")
for e in staffList:
  print({k: e[k] for k in ('Department', 'Salary', 'Name')})

Upvotes: 1

Gabio
Gabio

Reputation: 9504

You can use OrderedDict:

 from collections import OrderedDict

 staffList = []
 fields_order = ["Department", "Salary", "Name"]
 for data in staffFile:
     o_d = OrderedDict()
     for field in fields_order:
        o_d[field] = data["field"]
     staffList.append(o_d)
 return staffList

Upvotes: 0

Related Questions