Dictionaries and Objects, Labeled Data

Lists work when position carries meaning. But most real data has labels: a person has a name, an age, a city, not an item 0, item 1, item 2.

A Python dictionary and a JavaScript object both store key → value pairs. You look things up by name instead of position.

Labeled records

PYTHON

elder = {
    "name": "Fannie Lou Hamer",
    "born": 1917,
    "state": "Mississippi"
}
print(elder["name"])

JAVASCRIPT

let elder = {
  name: "Fannie Lou Hamer",
  born: 1917,
  state: "Mississippi"
};
console.log(elder.name); 
Compare → Curly braces and key: value pairs in both. Two real differences: Python REQUIRES quotes around keys; JavaScript usually omits them. And Python accesses with square brackets, elder["name"], while JavaScript prefers dot notation, elder.name (though elder["name"] also works).
EXAMPLE
loading editor…
YOUR TURN
Your turn → Assigning to a key that doesn't exist CREATES it. Add a field for a notable quote, then print the whole record.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Now the pattern that makes real applications possible: a list of dictionaries (Python) or an array of objects (JavaScript). This is how nearly every dataset on earth is shaped, every API response, every database query result, every spreadsheet.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Read it in two steps: users[1] gets the second record, then.name reaches inside it. Add a third user and print their age.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Sets, Uniqueness and Membership →
← Back