Use nested dictionaries or dict of class?

Python 3.12 with virtualenv on Windows 10 Pro. I’m still pretty new to Python. This was not something covered in my Python tutorial.

I’m actually converting an old Perl program to Python.

I have to loop through a database to gather data about an unknown number of employees. Each employee will have data like Firstname, Lastname, Hours worked, pieces produces, and some other stuff. I’m unsure whether to use a nested dictionary or dictionary of classes. I’m not even sure a dictionary of classes can be done.

What should a noob like me do for this case?

Here’s my test program for a nested dict which works.

mydict = {'1000': {'fname':'Tom', 'lname':'Smith', 'hours':1.8, 'pieces':35}, 
    '2000': {'fname':'Jim', 'lname':'Green' }}
print('One name for 1000:',mydict['1000']['fname'])
id = '2000'
print(f"For id {id}:",mydict[id]['fname'], mydict[id]['lname'])

After I get the data and process it I have to output an Excel file with a bunch of columns sorted by the employee ID, which is the dictionary key here with ‘1000’, ‘2000’.

EDIT 1: I don’t have to do anything fancy, Python is pretty fast. But I’m looking for major mistakes or issues I may miss.

Use whichever. I would use nested dictionaries, unless I have a specific need for the values to be instances of a custom class, like a dataclass. For example, if I had to do some sort of validation or transformation on the data, if different types of data require different kinds of transformations, then perhaps I would use custom classes.

Naming a variable id takes the name away from the built-in function id. Consider using a different name.


Franklinvp’s answer is good!

I just wanted to answer your other question: even though dictionaries of (instances of) classes are probably overkill for this, they are perfectly doable in Python and work much as you would expect.

You’re right. I missed that.