Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert Javascript dictionary to Python dictionary?
Converting JavaScript dictionaries (objects) to Python dictionaries requires an intermediate format since these languages handle data structures differently. JSON (JavaScript Object Notation) serves as the perfect bridge between JavaScript and Python for data exchange.
Understanding Python Dictionaries
In Python, a dictionary is a collection of unique key-value pairs. Unlike lists which use numeric indexing, dictionaries use immutable keys like strings, numbers, or tuples. Dictionaries are created using {} and allow you to store, retrieve, or delete values using their keys.
# Creating a Python dictionary
student = {
'name': 'Alice',
'age': 20,
'grades': [85, 90, 78]
}
print(student)
print(student['name'])
{'name': 'Alice', 'age': 20, 'grades': [85, 90, 78]}
Alice
Method 1: Using JSON for Conversion
The most common approach is using JSON as an intermediate format. First, convert the Python dictionary to JSON, then parse it in JavaScript ?
Python to JSON
import json
python_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'skills': ['Python', 'JavaScript', 'SQL']
}
# Convert Python dictionary to JSON string
json_string = json.dumps(python_dict)
print(json_string)
print(type(json_string))
{"name": "John", "age": 30, "city": "New York", "skills": ["Python", "JavaScript", "SQL"]}
<class 'str'>
JSON to Python Dictionary
When receiving JSON data from JavaScript, convert it back to a Python dictionary using json.loads() ?
import json
# JSON string (typically received from JavaScript)
json_data = '{"name": "Sarah", "age": 25, "department": {"name": "Engineering", "floor": 3}}'
# Convert JSON string to Python dictionary
python_dict = json.loads(json_data)
print(python_dict)
print(python_dict['department']['name'])
{'name': 'Sarah', 'age': 25, 'department': {'name': 'Engineering', 'floor': 3}}
Engineering
Method 2: Direct String Manipulation
For simple cases, you can manually convert JavaScript object syntax to Python dictionary format ?
# JavaScript object syntax (as string)
js_object_str = "{'name': 'Bob', 'score': 95, 'active': true}"
# Convert JavaScript boolean to Python
js_object_str = js_object_str.replace('true', 'True').replace('false', 'False')
# Evaluate as Python dictionary
python_dict = eval(js_object_str)
print(python_dict)
print(type(python_dict))
{'name': 'Bob', 'score': 95, 'active': True}
<class 'dict'>
Working with Complex Data Types
JSON handles nested objects, arrays, and common data types seamlessly ?
import json
complex_dict = {
'user': {
'id': 123,
'profile': {
'name': 'Alice Johnson',
'email': 'alice@example.com'
}
},
'orders': [
{'id': 1, 'total': 99.99},
{'id': 2, 'total': 149.50}
],
'active': True,
'balance': None
}
json_output = json.dumps(complex_dict, indent=2)
print(json_output)
{
"user": {
"id": 123,
"profile": {
"name": "Alice Johnson",
"email": "alice@example.com"
}
},
"orders": [
{
"id": 1,
"total": 99.99
},
{
"id": 2,
"total": 149.5
}
],
"active": true,
"balance": null
}
Key Differences Between JavaScript and Python
| Aspect | JavaScript | Python |
|---|---|---|
| Boolean values |
true, false
|
True, False
|
| Null value | null |
None |
| String quotes | Single or double | Single or double |
| Object notation | {key: value} |
{'key': value} |
Conclusion
Use json.dumps() to convert Python dictionaries to JSON strings for JavaScript consumption. Use json.loads() to parse JSON data from JavaScript back into Python dictionaries. This approach ensures proper data type conversion and maintains data integrity across both languages.
