Key-Value pair concept
What you'll learn: How to organize data by linking a unique identifier to a specific piece of information.
Up to this point, you have likely stored data in arrays. In an array, you find an element by its numeric position (index 0, 1, 2...). But in the real world, we rarely look things up by a position number. Instead, we use a label. This is the heart of the Key-Value pair concept.
The Locker Analogy
Imagine a wall of gym lockers. Each locker has a Key (the unique number etched on the metal tag) and a Value (the bag or shoes stored inside).
If you want your gear, you don't count "the 15th locker from the left." You look for the specific key labeled "Locker #402." The key is what you use to find the data, and the value is the data itself. In programming, a Key-Value pair is a simple association where one unique piece of data (the key) points to another piece of data (the value).
Why use them?
In C, we use these pairs to make data retrieval intuitive. Instead of remembering that "Employee 50" is stored at array[49], we can create a relationship where the ID string "EMP50" directly maps to a struct containing the employee's name and salary.
The most important rule is that Keys must be unique. Just as two people can't have different lockers with the same number, you cannot have two identical keys in a data structure. If you did, the computer wouldn't know which value to give you back!
How it looks in C
While C doesn't have a built-in "Dictionary" type like Python, we conceptually build these pairs using structures.
#include <stdio.h>
struct Entry {
int key; // The unique ID (e.g., Student ID)
char value[50]; // The data (e.g., Student Name)
};
int main() {
// Associating the key 101 with the value "Alice"
struct Entry student1 = {101, "Alice"};
printf("Key: %d maps to Value: %s\n", student1.key, student1.value);
return 0;
}
Key takeaway
A Key-Value pair is a relationship where a unique Key acts as a label to retrieve a specific Value.