Structs → Classes & Dicts
Grouping related data together
Introduction
In this lesson, you'll learn about structs → classes & dicts in Python. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with grouping related data together.
Python has its own approach to grouping related data together, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
score: float
def greet(self) -> str:
return f"Hi, I'm {self.name}"
alice = Person("Alice", 30, 9.5)
print(alice.greet())
print(alice) # Person(name='Alice', age=30, score=9.5)
# Or use a plain dict for simple data
person = {"name": "Alice", "age": 30}
print(person["name"])Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int age;
float score;
} Person;
Person create_person(const char *name, int age, float score) {
Person p;
strncpy(p.name, name, sizeof(p.name));
p.age = age;
p.score = score;
return p;
}
void print_person(const Person *p) {
printf("Name: %s, Age: %d\n", p->name, p->age);
}
Person alice = create_person("Alice", 30, 9.5f);
print_person(&alice);You may be used to different syntax or behavior.
C structs are pure data; Python classes add methods
You may be used to different syntax or behavior.
Python @dataclass auto-generates __init__, __repr__, __eq__
You may be used to different syntax or behavior.
Python dicts can replace simple C structs for dynamic data
You may be used to different syntax or behavior.
No typedef needed in Python — class defines the type directly
Step-by-Step Breakdown
1. Dataclass
Python's @dataclass decorator generates the constructor and string representation automatically, replacing C's manual struct initialization.
typedef struct { char name[50]; int age; } Person;@dataclass
class Person:
name: str
age: int2. Methods
Python classes combine data and behavior; C requires separate functions that take a struct pointer.
void print_person(const Person *p) { ... }def greet(self) -> str:
return f"Hi, I'm {self.name}"3. Dictionaries
For quick, dynamic groupings without a formal class, Python dicts are a lighter alternative to defining a struct.
config = {"host": "localhost", "port": 8080}
print(config["host"])Common Mistakes
When coming from C, developers often make these mistakes:
- C structs are pure data; Python classes add methods
- Python @dataclass auto-generates __init__, __repr__, __eq__
- Python dicts can replace simple C structs for dynamic data
Key Takeaways
- C struct → Python class or dict
- @dataclass generates __init__ and __repr__ automatically
- Classes can have methods; C structs cannot
- Dicts work for dynamic, untyped key-value data