How to convert Javascript dictionary to Python dictionary?



Python Dictionary

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. Lists cannot be keys since they are mutable. Dictionaries are created using {} and store, retrieve, or delete values using their keys. The list() function returns all keys, sorting them. The in keyword checks for key existence, and replacing a key updates its value.

Converting JavaScript to a Python Dictionary

Python and JavaScript represent dictionaries differently, so an intermediate format is needed to exchange data between them. The most widely used format for this purpose is JSON, a lightweight and simple data-interchange format. JSON makes it easy to transfer structured data between programming languages, ensuring compatibility and readability.

import json
my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict)
print(my_json)

The result is obtained as follows -

{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}

Example

This Python code uses the json.loads() function to convert a JSON-formatted string into a dictionary. JSON is a common format for storing and exchanging data.In this example, the string my_str represents a structured JSON object with nested key-value pairs. The json.loads(my_str) function reads this structure and converts it into a Python dictionary(my_dict). This program accesses a nested value using my_dict.

import json
my_str = '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'
my_dict = json.loads(my_str)
print(my_dict['bar']['baz'])

The result is obtained as follows -

Hello

In JavaScript, we don't need to process JSON because it stands for JavaScript Object Notation. JavaScript automatically creates objects from JSON data. If we receive a JSON-formatted string, we can easily convert it into a JavaScript object using JSON.parse(). This makes the data simple and efficient.

Updated on: 2025-09-01T14:47:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements