Objects vs Dictionaries
Key-value data structures
Introduction
In this lesson, you'll learn about objects vs dictionaries in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with key-value data structures.
Python has its own approach to key-value data structures, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
person = {"name": "Alice", "age": 30}
# Access
print(person["name"]) # bracket only
print(person.get("age", 0)) # safe access with default
# Mutate
person["city"] = "Istanbul"
del person["age"]
# Iteration
for key, val in person.items():
print(key, val)
# Unpacking
name = person["name"]
city = person.get("city", "Unknown")
# Merge (Python 3.9+)
updated = {**person, "age": 31}Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
const person = { name: "Alice", age: 30 };
// Access
console.log(person.name); // dot notation
console.log(person["age"]); // bracket notation
// Mutate
person.city = "Istanbul";
delete person.age;
// Iteration
for (const [key, val] of Object.entries(person)) {
console.log(key, val);
}
// Destructuring
const { name, city = "Unknown" } = person;
// Spread
const updated = { ...person, age: 31 };You may be used to different syntax or behavior.
Python dicts require string keys in quotes
You may be used to different syntax or behavior.
Use .get(key, default) for safe access
You may be used to different syntax or behavior.
dict.items() ≈ Object.entries()
You may be used to different syntax or behavior.
{**dict1, **dict2} ≈ {...obj1, ...obj2}
Step-by-Step Breakdown
1. Key Access
Python dicts only support bracket notation. Use .get() for safe access with a default value.
person.name
person["name"]person["name"]
person.get("name", "default")2. Iteration
Use .items() to get key-value pairs, .keys() for keys, .values() for values.
Object.entries(obj) // [[k,v], ...]
Object.keys(obj) // [k, ...]
Object.values(obj) // [v, ...]d.items() # dict_items
d.keys() # dict_keys
d.values() # dict_values3. Merging Dictionaries
Python 3.9+ supports the | merge operator and ** unpacking in dict literals.
const merged = { ...a, ...b };merged = {**a, **b} # Python 3.5+
merged = a | b # Python 3.9+Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Python dicts require string keys in quotes
- Use .get(key, default) for safe access
- dict.items() ≈ Object.entries()
Key Takeaways
- bracket access only — no dot notation
- .get(key, default) for safe lookups
- .items() / .keys() / .values() for iteration