If you have worked with JavaScript before, you might notice something interesting when learning Python.
Python dictionaries look almost identical to JavaScript objects!
Let's understand why they look similar, how they work, and what makes them different.
1. What is a Python Dictionary?
A dictionary is a built-in Python data structure that stores information in key-value pairs.
For example:
student = {
"name": "Raja",
"age": 22,
"course": "IT"
}
Here:
-
"name"is a key, and"Raja"is its value. -
"age"is a key, and22is its value. -
"course"is a key, and"IT"is its value.
We use keys to access the corresponding values.
2. Why Does It Look Like a JavaScript Object?
If you know JavaScript, you might have already used objects.
Let's compare both.
Python Dictionary:
student = {
"name": "Raja",
"age": 22,
"course": "IT"
}
JavaScript Object:
const student = {
name: "Raja",
age: 22,
course: "IT"
};
Both use key-value pairs to organize information.
That's why their syntax looks so similar!
3. How Do We Access Values?
Both Python dictionaries and JavaScript objects allow us to access values using their keys.
Python:
student = {"name": "Raja"}
print(student["name"])
Output:
Raja
JavaScript:
const student = {name: "Raja"};
console.log(student.name);
Output:
Raja
Notice that Python commonly uses square brackets, while JavaScript also supports dot notation.
4. Are Python Dictionaries and JavaScript Objects the Same?
No! Although they look similar, they have some important differences.
| Feature | Python Dictionary | JavaScript Object |
|---|---|---|
| Syntax | {} |
{} |
| Data storage | Key-value pairs | Properties |
| Key types | Any hashable type | Strings or symbols |
| Mutable | Yes | Yes |
| Access | d["name"] |
obj.name |
| Insertion order | Preserved | Special ordering rules for integer-like keys |
5. An Interesting Difference: Dictionary Keys
One interesting feature of Python dictionaries is that they support different types of keys, as long as those keys are hashable.
For example:
data = {
10: "Python",
(1, 2): "Tuple",
"name": "Raja"
}
print(data[10])
Output:
Python
Here, we used:
- Integer as a key.
- Tuple as a key.
- String as a key.
But can we use a list as a dictionary key?
data = {
[1, 2]: "Hello"
}
No! Python raises:
TypeError: unhashable type: 'list'
Why? Because lists are mutable, and dictionary keys must be hashable.
Conclusion
Python dictionaries and JavaScript objects look similar because both organize data using key-value pairs.
However, they are not exactly the same. Python dictionaries have their own rules, especially when it comes to key types and accessing values.
If you already know JavaScript objects, understanding Python dictionaries will be much easier!
Top comments (0)