0

I have a csv file with a name the first column and either A or B in the second. I want to analyse this (what group their in) and put there names into the corresponding text box in tkinter, how would i go about this?

from tkinter import *
import csv

master=Tk()

file=open(file="Book1.csv")
f=csv.reader(file)
people=[]
for column in f:
    people.append(column[0:2])


classAl=Label(master,text='A',width=10).grid(row=1,column=1)
classA=Text(master,width=10)
classA.grid(column=1,row=2)

classbl=Label(master,text='B',width=10).grid(row=1,column=2)
classB=Text(master,width=10)
classB.grid(column=2,row=2)

print(people)

grouplist=[x[1] for x in people]
for names in(grouplist):
    print(names)

this is the coding i have so far, i can read what group they are in but i'm not sure on how to then put its corresponding name into the correct place. any help would be appreciated.

Tom Lowbridge
  • 879
  • 3
  • 9
  • 17

1 Answers1

1

Use a collections.defaultdict to group the contents of your csv file by label (see this other stackoverflow question)

A Listbox would be more appropriate widget for your application.

import csv
from collections import defaultdict
from tkinter import *

grouped = defaultdict(list)

# Open the csv file and use the defaultdict to group by label.
with open('Book1.csv', 'r') as fh:
    book = csv.reader(fh)
    for name, label in book:
        grouped[label].append(name)

master = Tk()
A_label = Label(master, text='A', width=10).grid(row=1, column=1)
A_list = Listbox(master, width=10)
A_list.grid(column=1, row=2)
for name in grouped['A']:
    A_list.insert(END, name)

B_label = Label(master, text='B', width=10).grid(row=1, column=2)
B_list = Listbox(master, width=10)
B_list.grid(column=2, row=2)
for name in grouped['B']:
    B_list.insert(END, name)

master.mainloop()

It is better to open and read the csv file using the with statement (context manager).

I applied some general pep8 recommendations to the code as well.

Community
  • 1
  • 1
MarcelK
  • 110
  • 1
  • 7