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 create Python dictionary from JSON input?
You can parse JSON data into a Python dictionary using the json module. This module provides methods to convert JSON strings or files into Python dictionaries, allowing you to work with the data using familiar dictionary operations.
Creating Dictionary from JSON String
The most common approach is using json.loads() to parse a JSON string ?
import json
json_string = '''
{
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
'''
data = json.loads(json_string)
print(type(data))
print(data)
<class 'dict'>
{'id': 'file', 'value': 'File', 'popup': {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}}
Accessing Dictionary Values
Once converted to a dictionary, you can access values using standard dictionary methods ?
import json
json_string = '''
{
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"}
]
}
}
'''
data = json.loads(json_string)
# Access top-level values
print("ID:", data["id"])
print("Value:", data["value"])
# Access nested values
menu_items = data["popup"]["menuitem"]
print("First menu item:", menu_items[0]["value"])
ID: file Value: File First menu item: New
Iterating Through Dictionary
You can loop through the dictionary keys and values like any Python dictionary ?
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
for key, value in data.items():
print(f"Key: {key}")
print(f"Value: {value}")
print("---")
Key: name Value: John --- Key: age Value: 30 --- Key: city Value: New York ---
Loading from JSON File
For JSON data stored in files, use json.load() instead of json.loads() ?
import json
# Reading from a JSON file
with open('data.json', 'r') as file:
data = json.load(file)
# Now data is a dictionary
for key, value in data.items():
print(f"{key}: {value}")
Comparison
| Method | Input Type | Use Case |
|---|---|---|
json.loads() |
JSON string | When JSON data is in a string variable |
json.load() |
JSON file | When JSON data is stored in a file |
Conclusion
Use json.loads() for JSON strings and json.load() for JSON files. Both methods return a Python dictionary that you can manipulate using standard dictionary operations.
