Skip to main content

Python: dicts vs. classes

I like to "keep it simple stupid" when I'm coding Python. I use classes, but I don't try to shove everything into classes. When all you need is a dict or a list, use a dict or a list. However, I'm coming to think that if you have a bunch of objects that look like the following:

books = [{
  "authors": ["Neil Gaiman"],
  "title": "American Gods",
  "isbn": "9780062113450"

Then it might be time to use a class rather than a dict. In this case, I'd create a class called Book, but I'd put Book instances into a simple list.


Kevin H said…
I'd use namedtuple for that. But maybe that's just me.
David Goodger said…
For a simple collection of data without specialized behavior, I also use namedtuple, or a "Bunch" class (see the comments for variations). But add in custom behavior (methods), and of course a class is just the ticket. (Of course, namedtuple is just a quick and dirty way to implement a minimal-behavior class. Look up its implementation in the collections module.)

The nice thing about namedtuple (and Bunch) is that when behavior needs to be added, the namedtuple definition can easily be replaced by a class definition, without affecting the rest of the code.
David Goodger said…
The advantage of a Bunch over a namedtuple is that a Bunch is mutable: you can add, remove, and modify attributes in-place. But namedtuple has a built-in order. Your choice.
jjinux said…
Thanks for the comments, guys :)

I thought about using namedtuples, but decided to just go ahead and write out a class. In retrospect, it was the right thing, but my code assumes the instances are mutable.

The Bunch class is nice, but I think have the benefit of creating a class like this is to a) give it a name b) document what attributes you expect to be in it.

It'd be nice if Python had something to let me create a simple class with a set of attributes really quickly, kind of like a case class in Scala.
Craig Maloney said…
I'd love to know how to make a list of classes searchable without having to iterate over each record in turn. Is there a way to do that easily or am I stuck with iterating over lists?
yacc said…
Actually one can just subclass from named tuple, alternatively verbose=True gives you the source to paste.

Named tuples have a number of benefits, a central one being a tuple hence immutable. Add in some properties, and methods and you get a really nice object lite with a slight functional touch (as the value cannot be changed,which makes reasoning about the code so much easier)
Art Zemon said…
If you want something that is "just a little bit" more than a dict, you can create a class derived from a dict. See UserDict
jjinux said…
Thanks for the great comments, yacc and Art!
jjinux said…
> I'd love to know how to make a list of classes searchable without having to iterate over each record in turn. Is there a way to do that easily or am I stuck with iterating over lists?

Do it the same way databases do it. Create indexes of some sort, either via dicts or some sort of tree.

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from